How does the shell determine the number of input parameters?

In Shell scripts, the number of input parameters can be determined using the $# variable, which represents the number of parameters passed to the script.

Here is a sample script for determining the number of input parameters.

#!/bin/bash

if [ $# -eq 0 ]; then
    echo "No arguments provided."
elif [ $# -eq 1 ]; then
    echo "One argument provided."
else
    echo "More than one argument provided."
fi

In the above examples, the value of $# is determined by the if condition. If $# is 0, it means no parameters have been passed; if $# is 1, it means only one parameter has been passed; otherwise, it means multiple parameters have been passed.

You can run the script in the terminal and pass a different number of parameters for testing. For example:

$ ./script.sh
No arguments provided.

$ ./script.sh arg1
One argument provided.

$ ./script.sh arg1 arg2 arg3
More than one argument provided.
Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds