linux poison RSS
linux poison Email

Bash script: Using shift statement to loop through command line arguments

A shift statement is typically used when the number of arguments to a command is not known in advance and it takes a number (N), in  which the positional parameters are shifted to the left by this number, N.

Say you have a command that takes 10 arguments, and N is 4, then $4 becomes $1, $5 becomes $2 and so on. $10 becomes $7 and the original $1, $2 and $3 are thrown away.

Below is the simple example showing the usage of 'shift' statements:

Source:  cat shift2.sh
#!/bin/bash

echo "Total number of arg passed: $#"
echo "arg values are: $@"
echo "-----------------------------------------"

while [[ $# > 0 ]] ; do
        echo "\$1 = $1"
        shift
done

echo

Output: ./shift2.sh a b c d e f
Total number of arg passed: 6
arg values are: a b c d e f
-----------------------------------------
$1 = a
$1 = b
$1 = c
$1 = d
$1 = e
$1 = f






0 comments:

Post a Comment

Related Posts with Thumbnails