Examples of “shift” Command in Shell Scripts

The shift Statement

Sometimes a script does not require a specific number of arguments from users. Users are allowed to give as many arguments to the script as they want. In these situations, the arguments of the script are usually processed in a while loop with the condition being (($#)). This condition is true as long as the number of arguments is greater than zero. Within the script $1 and the shift statement process each argument. Because doing a shift reduces the argument number, eventually, the condition in the while loop becomes false and the loop terminates.

NOTE: If no number is supplied as an argument to the shift statement, the number is assumed to be 1.

The syntax for the shift statement is:

$ shift [ num ]

All positional parameters are shifted to the left the number of positions indicated by num (or by 1 if num is omitted).

The number of left-most parameters are eliminated after the shift. For example, the statement:

$ shift 4

eliminates the first four positional parameters. The value of the fifth parameter becomes the value of $1, the value of the sixth parameter becomes the value of $2, and so on. It is an error for num to be larger than the number of positional parameters.

Example of Using the shift Statement

The following shift.ksh example script contains a USAGE message showing that the script should be run with arguments, although the number of arguments given is variable:

$ cat shift.ksh 
#!/bin/ksh

# Script name: shift.ksh

USAGE="usage: $0 arg1 arg2 ... argN"

if (( $# == 0 )) 
then
        print $USAGE
        exit 1 
fi
print "The arguments to the script are:" 
while (($#)) 
do
        print $1 
    shift 
done
print 'The value of $* is now:'' $*

If the user does not provide arguments, the USAGE message is printed and the script exits; otherwise, the while loop is entered. Each time through the loop, the current value of the positional parameter, $1, is printed and the shift statement executes.

The shift statement reduces the number of arguments by one as it shifts the values of the positional parameters one position to the left. ($1 is assigned the value of $2, $2 is assigned the value of $3, and so on, while the value of $1 is discarded). After each argument is printed, the condition of (($#)) is false, and the while loop terminates. The statement print $* shows that nothing is printed after the execution of the while loop because the value of $# is 0.

The values of the positional parameters are set to letters of the alphabet using the set statement and printed using the statement print $* (to show the new values of the positional parameters). The last two statements in the script, shift 4 and print $*, illustrate what occurs when a larger shift is made.

$ ./shift.ksh one two three four 
The arguments to the script are: 
one 
two 
three 
four 
The value of $* is now:
Related Post