Bootstrap FreeKB - Bash (Scripting) - shift command line options
Bash (Scripting) - shift command line options

Updated:   |  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 Buy Me A Coffee



Comments


Add a Comment


Please enter cc956b in the box below so that we can be sure you are a human.