variables
shift
Renames positional parameters: $2 becomes $1, $3 becomes $2, and so on, decrementing $#. Optional N shifts by N positions and is common in manual argument parsing loops.
shift [N] Common flags / operators
| Flag / Operator | Purpose |
|---|---|
| N | Number of positions to shift (default 1) |
| exit status | Non-zero if N > $# (nothing to shift) |
| affects $@ | $@ and $* update accordingly |
| no options | Only takes the numeric argument |
Examples
while (( $# )); do echo "$1"; shift; done Iterate all positional arguments consumingly.
cmd=$1; shift; "$cmd" "$@" Pop the first arg as a command, pass rest through.
case $1 in -v|--verbose) verbose=1; shift;; esac Consume a flag in a hand-rolled arg parser.
shift 3 Drop the first three positional parameters.
Gotcha
'shift' inside a function shifts the FUNCTION's parameters, not the script's. Shifting more than $# leaves parameters unchanged and returns non-zero — check the status if it matters.
Related
return
Exits a shell function or sourced script and returns exit status N (0-255). Without N, returns the exit status of the last command executed in the function.
case ... esac
Pattern-matches a word against glob-style patterns (not regex) and runs the first matching branch. Terminators control fall-through: ;; ends, ;& falls through, ;;& tries next pattern.
set (options)
Changes shell option flags and/or replaces positional parameters. The 'safer bash' idiom 'set -euo pipefail' is the most common use — it turns on error-exit, unset-variable-error, and pipeline failure propagation.
export
Marks a shell variable (or function with -f) for export to the environment of subsequently executed commands. Without arguments, prints all exported variables in a re-importable format.
unset
Removes a variable or function from the shell — different from setting it to empty. Without a flag it targets variables first, then functions, unless -f or -v is specified.