A shell script can handle any number of input arguments using the special variable $#, which represents the number of arguments passed to the script. You can use conditional statements to check how many arguments were provided and respond accordingly. Here's an example:
#!/bin/bash
if [ $# -eq 0 ]; then
echo "No arguments provided."
elif [ $# -eq 1 ]; then
echo "One argument provided: $1"
elif [ $# -eq 2 ]; then
echo "Two arguments provided: $1 and $2"
else
echo "More than two arguments provided:"
echo "First argument: $1"
echo "Second argument: $2"
echo "Third argument: $3"
echo "Total number of arguments: $#"
fi
Explanation:
if [ $# -eq 0 ]: Checks if no arguments are provided.elif [ $# -eq 1 ]: Checks if one argument is provided.elif [ $# -eq 2 ]: Checks if two arguments are provided.- The
elseblock handles cases where more than two arguments are provided.
You can test this script by running it with different numbers of arguments, like so:
./script.sh
./script.sh arg1
./script.sh arg1 arg2
./script.sh arg1 arg2 arg3 arg4
This will demonstrate how the script responds based on the number of arguments given.
