Shell shift procedure - What is this?

user1253622 picture user1253622 · May 2, 2012 · Viewed 46.9k times · Source

In shell we have the command shift, but i saw on some example its giving shift 3

Why there is a number after shift ? and what its about ? what it does ?

Example:

echo “arg1= $1  arg2=$2 arg3=$3”
shift
echo “arg1= $1  arg2=$2 arg3=$3”
shift   
echo “arg1= $1  arg2=$2 arg3=$3”
shift  
echo “arg1= $1  arg2=$2 arg3=$3”
shift

The output will be:

arg1= 1 arg2=2  arg3=3 
arg1= 2 arg2=3  arg3= 
arg1= 3 arg2=   arg3=
arg1=   arg2=   arg3=

But when i add that, it doesn't display it correctly.

Answer

dogbane picture dogbane · May 2, 2012

Take a look at the man page, which says:

shift [n]
    The  positional parameters from n+1 ... are renamed to $1 .... 
    If n is not given, it is assumed to be 1.

An Example script:

#!/bin/bash
echo "Input: $@"
shift 3
echo "After shift: $@"

Run it:

$ myscript.sh one two three four five six

Input: one two three four five six
After shift: four five six

This shows that after shifting by 3, $1=four, $2=five and $3=six.