Positional Parameters and shift
The variables $1, $2, $3 and so on are called positional parameters, because each one is identified by its position in the argument list. They are not fixed: Bash lets you remove the first one with shift, replace the whole list with set --, and read parts of the list with slices. These tools make it possible to process any number of arguments, however many the user supplies.
What Positional Parameters Are
When a script (or a function) starts, Bash fills the positional parameters from the words that follow its name. Three related values always describe the current list:
$1,$2, ... hold the individual arguments.$#holds how many there are."$@"expands to all of them.
Everything in this lesson changes that list, and $# and "$@" always reflect the change. The previous lessons showed how to read the list. This lesson shows how to modify it.
Removing the First Argument with shift
The shift built-in discards $1, moves every remaining argument one place to the left, and reduces $# by one:
cat > s1.sh <<'EOF'
echo "before: \$1=$1 \$2=$2 \$3=$3 \$#=$#"
shift
echo "after shift: \$1=$1 \$2=$2 \$3=$3 \$#=$#"
shift 2
echo "after shift 2: \$1=[$1] \$#=$#"
EOF
bash s1.sh a b c d
before: $1=a $2=b $3=c $#=4
after shift: $1=b $2=c $3=d $#=3
after shift 2: $1=[d] $#=1
The steps work like this:
- The script starts with four arguments:
a b c d. shiftremovesa. What used to be$2(b) is now$1, and the count drops to 3.shift 2removes two more arguments (bandc). Onlydis left, and it is now$1.
A removed argument cannot be recovered through $1, so save any value you still need before shifting. The name of the script in $0 is not part of the list and is never changed by shift.
Shifting Too Far
shift N needs at least N arguments. If you ask for more than exist, nothing is removed and the command returns status 1, silently:
cat > s2.sh <<'EOF'
echo "args: $#"
shift 5
echo "status=$? args now: $#"
shift 0
echo "shift 0: status=$? args now: $#"
EOF
bash s2.sh a b
args: 2
status=1 args now: 2
shift 0: status=0 args now: 2
shift 5 failed and left both arguments in place, while shift 0 is allowed and does nothing. Because a failed shift prints no message, test the count first or check the status when a script depends on it:
cat > s14.sh <<'EOF'
shift 3 2>/dev/null || echo "not enough arguments to shift (status $?)"
EOF
bash s14.sh a
not enough arguments to shift (status 1)
A negative or non-numeric count is an error with a message:
cat > s15.sh <<'EOF'
shift -1
echo "status=$?"
EOF
bash s15.sh a b
s15.sh: line 1: shift: -1: shift count out of range
status=1
Looping Through All Arguments with shift
A loop that repeatedly handles $1 and then shifts is the classic way to process an unknown number of arguments:
cat > s4.sh <<'EOF'
#!/usr/bin/env bash
while (( $# > 0 )); do
echo "processing: $1 (remaining after this: $(( $# - 1 )))"
shift
done
echo "done, \$# is $#"
EOF
bash s4.sh alpha beta gamma
processing: alpha (remaining after this: 2)
processing: beta (remaining after this: 1)
processing: gamma (remaining after this: 0)
done, $# is 0
The condition (( $# > 0 )) is true while arguments remain. Each pass handles the current $1 and then shifts it away, so the loop ends when the list is empty.
If you only need to look at each argument and do not need to consume them, for arg in "$@" is simpler, and it leaves the list unchanged:
cat > s12.sh <<'EOF'
for arg in "$@"; do echo "for: $arg"; done
echo "\$# after for loop: $#"
EOF
bash s12.sh p q
for: p
for: q
$# after for loop: 2
Choose the while and shift pattern when the handling of one argument depends on the next one, which happens with options that take a value.
Parsing Options That Take a Value
An option such as -o out.txt consists of two words. The script handles the flag, then shifts once more to skip over the value:
cat > opts.sh <<'EOF'
#!/usr/bin/env bash
verbose=0
output=""
files=()
while [[ $# -gt 0 ]]; do
case $1 in
-v|--verbose)
verbose=1
;;
-o|--output)
if [[ $# -lt 2 ]]; then
echo "error: $1 needs a value" >&2
exit 1
fi
output=$2
shift
;;
*)
files+=("$1")
;;
esac
shift
done
echo "verbose=$verbose output=${output:-none}"
echo "files (${#files[@]}): ${files[*]}"
EOF
bash opts.sh -v -o out.txt a.txt b.txt
bash opts.sh -o
echo "exit=$?"
verbose=1 output=out.txt
files (2): a.txt b.txt
error: -o needs a value
exit=1
Here is how the first run is processed:
-vmatches the first pattern, soverbosebecomes1. Theshiftat the bottom of the loop removes it.-omatches the second pattern. The script saves$2(out.txt) inoutput, shifts once inside the branch to remove the flag, and the shift at the bottom of the loop removes the value.a.txtandb.txtmatch the*pattern and are added to an array of file names.
In the second run, -o was the last argument, so $# was 1 and the guard [[ $# -lt 2 ]] printed an error instead of reading a value that was not there. The case statement is covered later in the tutorial, and getopts offers a ready-made alternative for option parsing.
Taking the First Argument and Passing On the Rest
A frequent task is treating the first argument as a command or sub-command and forwarding everything else. Save the first argument, shift it away, and then use "$@" for the remainder:
cat > run.sh <<'EOF'
#!/usr/bin/env bash
cmd=$1
shift
echo "running: $cmd with $# arguments"
"$cmd" "$@"
echo "exit status: $?"
EOF
bash run.sh printf '[%s]\n' "a b" c
running: printf with 3 arguments
[a b]
[c]
exit status: 0
After shift, "$@" holds the three remaining arguments: the printf format and the values a b and c. The argument a b stayed in one piece because "$@" preserves each argument.
Replacing the List with set --
The set command can also overwrite the positional parameters. Everything after -- becomes the new list:
cat > s6.sh <<'EOF'
echo "initial: $# args: $*"
set -- red green blue
echo "after set --: $# args: $1 $2 $3"
set --
echo "after set -- with nothing: $# args"
set -- $(echo one two three)
echo "from command output: $# args, second=$2"
set -- "a b" c
echo "quoted: $# args, first=[$1]"
EOF
bash s6.sh x y
initial: 2 args: x y
after set --: 3 args: red green blue
after set -- with nothing: 0 args
from command output: 3 args, second=two
quoted: 2 args, first=[a b]
What each line does:
set -- red green bluethrows awayx yand installs three new arguments.set --with nothing after it empties the list, so$#is0.set -- $(...)splits the output of a command into words and loads them. Unquoted command output is split on whitespace, so use this form only when that splitting is what you want.- Quoting an item (
"a b") keeps it as a single argument.
The double dash -- marks the end of the options for set. It matters when a value starts with a dash, because without it set would try to read the value as one of its own options:
cat > s7.sh <<'EOF'
set -- -x -y
echo "with --: $# args: $1 $2"
EOF
bash s7.sh
with --: 2 args: -x -y
Reading Part of the List
"${@:offset}" and "${@:offset:length}" produce a slice of the arguments without changing the list:
cat > s8.sh <<'EOF'
echo "all: $@"
echo "from 2: ${@:2}"
echo "2 items from 2: ${@:2:2}"
echo "last: ${@: -1}"
echo "count after a slice: $(set -- "${@:2}"; echo $#)"
echo "original count still: $#"
EOF
bash s8.sh a b c d e
all: a b c d e
from 2: b c d e
2 items from 2: b c
last: e
count after a slice: 4
original count still: 5
Points to notice:
- Counting starts at
1, so${@:2}means "from the second argument to the end". ${@:2:2}takes two items starting at the second.- A negative offset counts from the end, but it needs a space after the colon, as in
${@: -1}. Without the space,${@:-1}would be read as the default-value form:-. - The slice inside the
$( ... )was taken in a subshell, so the original list was untouched. - The offset
0includes the script name as the first item, because$0is treated as position zero.
The last argument can also be fetched with indirect expansion, ${!#}, where # is the argument count and ! means "use that number as the position":
cat > s9.sh <<'EOF'
last=${!#}
echo "last arg: $last"
n=2
echo "argument number $n: ${!n}"
EOF
bash s9.sh first second third
last arg: third
argument number 2: second
The same indirect form, ${!n}, reads the argument whose number is stored in the variable n. This is how you read an argument by a computed position.
Functions Have Their Own Positional Parameters
Each function call gets a fresh list. Shifting inside a function changes only the function's copy:
cat > s10.sh <<'EOF'
f() {
echo "f start: \$1=$1 \$#=$#"
shift
echo "f after shift: \$1=$1 \$#=$#"
}
echo "main: \$1=$1 \$#=$#"
f x y z
echo "main after f: \$1=$1 \$#=$#"
EOF
bash s10.sh m1 m2
main: $1=m1 $#=2
f start: $1=x $#=3
f after shift: $1=y $#=2
main after f: $1=m1 $#=2
The script's own arguments m1 m2 were never touched. The same rule applies to set --:
cat > s11.sh <<'EOF'
f() { set -- changed; echo "in f: $1"; }
f
echo "main: $1"
EOF
bash s11.sh original
in f: changed
main: original
This isolation is what allows functions to be written like small scripts of their own. Lesson 89 returns to passing arguments to functions.