Bash (Scripting) - shift command line options

by
Jeremy Canfield |
Updated: March 24 2022
| Bash (Scripting) articles
Let's say "foo" and "bar" are passed into the example.sh script.
example.sh var1 var2 var3
In the example.sh script, var1 will be accessed using $1, var2 will be accessed using $2, and var3 will be accessed using $3.
#!/bin/bash
echo "\$0 = $0
echo "\$1 = $1"
echo "\$2 = $2"
echo "\$3 = $3"
Invoking this script will return the following output.
$0 = example.sh
$1 = var1
$2 = var2
$3 = var3
As the name implies, shift can be used to shift the values. Let's say you have the following.
#!/bin/bash
echo "before shift"
echo "\$0 = $0
echo "\$1 = $1"
echo "\$2 = $2"
echo "\$3 = $3"
shift;
echo "after shift"
echo "\$0 = $0
echo "\$1 = $1"
echo "\$2 = $2"
echo "\$3 = $3"
The following should be returned. Now $1 contains var2, $2 contain var3, and $3 contains no value.
before shift
$0 = example.sh
$1 = var1
$2 = var2
$3 = var3
after shift
$0 = example.sh
$1 = var2
$2 = var3
$3 =
You can shift multipe positions, such as shift 2.
#!/bin/bash
echo "before shift"
echo "\$0 = $0
echo "\$1 = $1"
echo "\$2 = $2"
echo "\$3 = $3"
shift 2;
echo "after shift 2"
echo "\$0 = $0
echo "\$1 = $1"
echo "\$2 = $2"
echo "\$3 = $3"
The following should be returned. Now $1 contains var3 and $2 and $3 contain no value.
before shift
$0 = example.sh
$1 = var1
$2 = var2
$3 = var3
after shift
$0 = example.sh
$1 = var3
$2 =
$3 =
Did you find this article helpful?
If so, consider buying me a coffee over at