The execution of scripts is made versatile by the ability to run a script based on arguments supplied on the command line. In this way, the operation of the script varies depending on what arguments are given to the script. The shell automatically assigns special variable names, called positional parameters, to each argument supplied to a script on the command line. The positional parameter names and meanings are shown in Table below.
Positional Parameter Name | Returns true (0) if: |
---|---|
$0 | The name of the script |
$1 | The first argument to the script |
$2 | The second argument to the script |
$n | The n-th argument to the script |
$# | The number of arguments to the script |
$@ | A list of all arguments to the script |
$* | A list of all arguments to the script |
${#N} | The length of the value of positional parameter N (Korn shell only) |
$@ and $* have the same meaning. This is true if they are not enclosed in double quotes ” “.
Using if loop to Check Command-Line Arguments
The following script captures the command-line arguments in special variables: $#, $1, $2, $3, and so on. The $# variable captures the number of command-line arguments. The following example use the command line arguments to do a comparison.
# cat arg.sh #!/bin/bash if [ $1 -gt $2 ] then echo "num1 is larger" else echo "num2 is larger" fi
You can run the above script as shown below.
$ ./a 23 45 num2 is larger