You can check the number of arguments passed to a shell script using the special variable $#, which represents the total number of arguments. Here’s an example:
#!/bin/bash
# Check the number of arguments
if [ $# -lt 2 ]; then
echo "Error: At least two arguments are required."
echo "Usage: $0 <arg1> <arg2> ..."
exit 1
fi
echo "Total number of arguments: $#"
In this script, if fewer than two arguments are provided, it will display an error message and usage instructions. To run this script, save it to a file (e.g., check_args.sh), make it executable with chmod +x check_args.sh, and execute it with different numbers of arguments:
./check_args.sh arg1 arg2
This will output:
Total number of arguments: 2
If you run it with fewer than two arguments, it will show the error message.
