Understanding Positional Parameters (Passing Parameters/Arguments to Shell script)

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 ” “.

Note – The Bourne shell stores all the arguments passed to the script, but can refer to only the positional parameters $1 through $9. To obtain the values beyond the ninth argument, use the shift statement, which is destructive in nature.

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
Related Post