Parse positional arguments with shift
Positional parameters form an ordered argument list. $1 is the first argument and $# is the number remaining. shift discards the first argument and renumbers the rest; shift 2 consumes two. It does not modify the caller’s positional parameters when used inside a function. Check the count before consuming arguments: shifting beyond the count fails. A common pattern is a while (( $# )); do ...; done loop with exactly one consumption step per recognized item. Keep quoted "$@" when forwarding the remaining vector. An explicit empty string is still an argument. For a fixed subcommand, validate its name and arity before doing work. An argument walker must consume an argument or stop. If printing fails, the example returns failure instead of continuing to consume input and possibly masking that error.
Practical examples
Run each example as a separate script in a fresh noninteractive Bash 5.2 process and empty practice directory. Tests use C locale; do not enter expected output as code.
Consume one argument
set -- show 'daily report' ''verb=$1shiftprintf 'verb=%s count=%s\n' "$verb" "$#"printf '[%s]\n' "$@"Expected stdout:
verb=show count=2[daily report][]After shift, two distinct operands remain, including the empty one.
Walk through arguments
walk() { while (( $# )); do printf '[%s]\n' "$1" || return 1 shift done}walk 'a b' '' '*' ''Expected stdout:
[a b][][*][]Each iteration consumes exactly one item. The literal star is not expanded.
Validate a fixed subcommand
dispatch() { if (( $# != 3 )) || [[ $1 != show ]]; then printf 'usage: show LEFT RIGHT\n' >&2 return 2 fi shift printf '[%s]\n' "$@"}dispatch show 'left side' rightExpected stdout:
[left side][right]The count is checked before shifting; operands are forwarded unchanged.
Common mistakes
If a branch of a parsing loop neither shifts nor exits, the loop can repeat indefinitely. Never replace "$@" with $* to forward arbitrary arguments.
Practice
Implement a show subcommand requiring exactly two operands. Test missing and extra operands, a space-containing operand and an empty operand. Decide whether empty values are allowed.
Next: Parse short options with getopts