Bash - Shift

1 - About

The shift utility permits to shift the argument (position parameters).

3 - Syntax


shift [n]

  • n is a non-negative number less than or equal to $#. Default to 1.

The positional parameters from n+1 … are renamed to $1 ….

Parameters represented by the numbers $# down to $#-n+1 are unset.

If n is:

  • 0, no parameters are changed.
  • not given, it is assumed to be 1.
  • greater than $#, the positional parameters are not changed.

The return status is greater than zero if n is greater than $# or less than zero; otherwise 0.

4 - Example

4.1 - Basic


while [ "" == "" ]; do
  
  if [ -z ${1+x} ]; then break; else echo "The positional parameter 1 is set to '$1'"; fi
  shift 1
  
done

  • Run

basicSwitchDemo.sh --option1 valueOption1 --option2=valueOption2 -3

  • Output:

The positional parameter 1 is set to '--option1'
The positional parameter 1 is set to 'valueOption1'
The positional parameter 1 is set to '--option2=valueOption2'
The positional parameter 1 is set to '-3'

4.2 - Option Parsing


while [ "" == "" ]; do
  case $1 in
    --option1)
        option1=$2
        echo The option1 is: $option1
        shift 2
        ;;
    --option2=?*)
        option2=${1#--option2=}
        echo The option2 is: $option2
        shift
        ;;
    [-+][0-9]*)
        num=$1
        echo The level is: $num
        shift
        ;;
    *)  echo $"$0: Usage: optionSwitchDemo.sh --option1 value1 --option2=value2 [+/-level]"
        exit 1;;
  esac
done
# If you don't want to fall done in the usage 
# the following condition can be use for the switch
# [ "$1" != "${1##[-+]}" ];

  • Run

optionSwitchDemo.sh --option1 valueOption1 --option2=valueOption2 -3

  • Output:

The option1 is: valueOption1
The option2 is: valueOption2
The level is: -3
/tmp/optionSwitchDemo.sh: Usage: optionSwitchDemo.sh --option1 value1 --option2=value2 [+/-level] 


Data Science
Data Analysis
Statistics
Data Science
Linear Algebra Mathematics
Trigonometry

Powered by ComboStrap