Being Shifty
Another tool you have in your bash shell tool belt is the shift
command. The bash shell provides the shift
command to help you manipulate command line parameters. The shift
command literally shifts the command line parameters in their relative positions.
When you use the shift
command, it moves each parameter variable one position to the left by default. Thus, the value for variable $3
is moved to $2
, the value for variable $2
is moved to $1
, and the value for variable $1
is discarded (note that the value for variable $0
, the program name, remains unchanged).
This is another great way to iterate through command line parameters, especially if you don't know how many parameters are available. You can just operate on the first parameter, shift the parameters over, and then operate on the first parameter again.
Here's a short demonstration of how this works:
$ cat test13.sh
#!/bin/bash
# demonstrating the shift command
echo
count=1
while [ -n "$1" ]
do
...