How to use if to Check Command-Line Arguments in Shell Scripts

Positional Parameters

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 the table below.

Positional Parameter Name Description
$0 The name of the script
$1 The first argument to the script
$2 The second argument to the script
$9 The ninth argument to the script
${10}, ${11},${n} The tenth and up argument to the script (Korn shell only)
$# 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 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 sets variables within a script.

$ cat numtest.ksh
#!/bin/ksh

# Script name: numtest.ksh

num1=5
num2=6

if (( $num1 > $num2 ))
then
    print "num1 is larger"
else
    print "num2 is larger"
fi

The following example shows changing the script so that you can enter command-line arguments:

$ cat argtest.ksh
#!/bin/ksh

# Script name: argtest.ksh

if (($1>$2))
then
    print "num1 is larger"
else
    print "num2 is larger"
fi

Do the following to execute the script:

$ ./argtest.ksh 21 11
num1 is larger
$ ./argtest.ksh 1 11
num2 is larger