< Previous | Contents | Next >
shift – Getting Access To Many Arguments
But what happens when we give the program a large number of arguments such as this:
[me@linuxbox ~]$ posit-param *
Number of arguments: 82
$0 = /home/me/bin/posit-param
$1 = addresses.ldif
$2 = bin
$3 = bookmarks.html
$4 = debian-500-i386-netinst.iso
$5 = debian-500-i386-netinst.jigdo
$6 = debian-500-i386-netinst.template
$7 = debian-cd_info.tar.gz
$8 = Desktop
$9 = dirlist-bin.txt
$8 = Desktop
$9 = dirlist-bin.txt
On this example system, the wildcard * expands into 82 arguments. How can we process that many? The shell provides a method, albeit a clumsy one, to do this. The shift command causes all the parameters to “move down one” each time it is executed. In fact, by using shift, it is possible to get by with only one parameter (in addition to $0, which never changes):
#!/bin/bash
# posit-param2: script to display all arguments count=1
while [[ $# -gt 0 ]]; do
echo "Argument $count = $1" count=$((count + 1))
shift done
#!/bin/bash
# posit-param2: script to display all arguments count=1
while [[ $# -gt 0 ]]; do
echo "Argument $count = $1" count=$((count + 1))
shift done
Each time shift is executed, the value of $2 is moved to $1, the value of $3 is moved to $2 and so on. The value of $# is also reduced by one.
In the posit-param2 program, we create a loop that evaluates the number of argu- ments remaining and continues as long as there is at least one. We display the current ar- gument, increment the variable count with each iteration of the loop to provide a run- ning count of the number of arguments processed and, finally, execute a shift to load
$1 with the next argument. Here is the program at work:
[me@linuxbox ~]$ posit-param2 a b c d
Argument 1 = a Argument 2 = b Argument 3 = c Argument 4 = d
[me@linuxbox ~]$ posit-param2 a b c d
Argument 1 = a Argument 2 = b Argument 3 = c Argument 4 = d