Positional Parameters and shift

Positional Parameters and shift in Bash: --- At the base of a chairlift, skiers line up in a single file along the loading rail.


The Analogy: The Ski-Lift Loading Queue

At the base of a chairlift, skiers line up in a single file along the loading rail. The lift operator does not know or care who any of them are; the operator only cares about position. The person at the very front of the rail is "next", the one behind is "the one after", and so on down the line. When a chair swings around, the operator loads the front skier, and the whole queue shuffles forward one place: the person who was second is now at the front, the third is now second, and everyone's position number drops by one. This shuffling-forward is the exact behaviour of a shell's positional parameters and the shift command.

In the shell, the arguments passed to a script or function are the skiers in the queue. $1 is whoever is at the front, $2 is next, and so on. The operator can glance down the line and count how many are still waiting -- that is $#, the number of parameters. The operator can also refer to the entire queue at once: "all the skiers" is $@. And when the front skier is loaded onto a chair and the line shuffles up, that is shift: the old $1 is discarded, the old $2 becomes the new $1, and $# drops by one. A busy operator loading a six-seater at once shuffles the queue forward by six, which is shift 6.

There is a subtlety in how you describe the queue as a whole, and it matters enormously. If the operator radios control and says "I have these skiers: Anna, Ben from Berlin, Chloe" with each name kept distinct, that is "$@" in double quotes -- each argument stays a separate item, boundaries intact, even if a name contains a space. If instead the operator mashes the whole line into one announcement -- "annabenfromberlinchloe" run together as a single blurted string -- that is "$*", which joins all the arguments into one word separated by the first character of IFS. For iterating over arguments safely, "$@" is almost always what you want; "$*" is for the rare case where you deliberately want one joined string.

The failure mode has two faces. The first is calling for a skier who is not there: asking for $5 when only three people are in line gives you nothing, an empty value, and under set -u it aborts the script with an unbound-variable error -- like the operator shouting "number five!" at an empty rail. The second is the multi-digit trap. If the operator has more than nine skiers and wants the tenth, pointing at "position 10" is not the same as pointing at "position 1, then a 0 painted on the ground": $10 is parsed as $1 followed by a literal 0, not the tenth parameter, which must be written ${10}. Both mistakes are silent until they produce a wrong value, which is why disciplined argument handling counts first and reaches for parameters second.


Syntax or Core Structure

Positional parameters are the arguments given to a script or function. Inside a function, $1 through $9 name the first nine arguments, ${10} and beyond need braces, $# is the count, and $@ is the whole list. This function reports on whatever it is called with.

#!/usr/bin/env bash
show() {
  echo "count: $#"
  echo "first: $1"
  echo "second: $2"
  echo "all: $@"
}
show apple banana cherry

Output:

count: 3
first: apple
second: banana
all: apple banana cherry

The call show apple banana cherry hands the function three arguments. $# reports 3, $1 is apple, $2 is banana, and $@ lists them all. Arguments are separated by whitespace at the call site, with no commas. Note that a function has its own set of positional parameters, distinct from the script's -- inside show, $1 is the function's first argument, not the script's. The same $1, $#, and $@ notation works at the top level of a script, where the parameters are the command-line arguments the script was invoked with.


Technical Depth: Quoting the List, Consuming with shift, and the Multi-Digit Trap

The parameter reference table

Five constructs cover almost all positional-parameter work. The two that cause the most confusion are "$@" and "$*", which look interchangeable and behave very differently.

ConstructMeaningBehaviour when quoted
the 1, 2, 3 formsone parameter by positionthe single value, brace ten and up
the hash formcount of parametersa plain integer
the at formall parameterseach parameter a separate word
the star formall parametersone word joined by first IFS char
shift Ndrop N front parametersrenumbers, decrements the count

"$@" keeps boundaries, "$*" collapses them

This distinction decides whether arguments with spaces survive. Quoted "$@" expands to one word per argument, preserving each; quoted "$*" expands to a single word with the arguments joined by the first character of IFS (a space by default).

#!/usr/bin/env bash
demo() {
  echo "iterating quoted at-sign:"
  for a in "$@"; do echo "  [$a]"; done
  echo "iterating quoted star:"
  for a in "$*"; do echo "  [$a]"; done
}
demo "new york" london "san francisco"

Output:

iterating quoted at-sign:
  [new york]
  [london]
  [san francisco]
iterating quoted star:
  [new york london san francisco]

With "$@" the loop runs three times, once per argument, and new york and san francisco keep their internal spaces as single items. With "$*" the loop runs exactly once, because the whole list has been fused into one string. The lesson is blunt: to iterate over arguments correctly, always write for a in "$@". Using $@ or $* unquoted would word-split every argument on its spaces, shattering new york into two items, and "$*" is only right when you genuinely want one joined string, such as building a single log line.

Consuming a queue with shift

The shift command discards $1 and renumbers the rest, which makes a while (( $# > 0 )) loop the standard way to walk arguments one at a time. $1 is always the current front of the queue.

#!/usr/bin/env bash
consume() {
  echo "starting with $# item(s)"
  while (( $# > 0 )); do
    echo "  head=$1  remaining=$#"
    shift
  done
  echo "queue empty"
}
consume a b c

Output:

starting with 3 item(s)
  head=a  remaining=3
  head=b  remaining=2
  head=c  remaining=1
queue empty

Each pass reads $1 -- always the current front -- then shift drops it and the count falls. After three shifts $# is zero and the loop ends. This renumbering is exactly the ski-lift queue shuffling forward. One caution: shift when there are no parameters left returns a non-zero status and, in older shells, can warn; the (( $# > 0 )) guard ensures you never shift an empty queue.

The multi-digit trap and shift N

Beyond nine parameters, the single-digit form breaks down, and shift can take a count to drop several at once.

#!/usr/bin/env bash
set -- one two three four five six seven eight nine ten
echo "dollar-1 then 0: $10"
echo "braces ten: ${10}"
shift 3
echo "after shift 3: first=$1 count=$#"

Output:

dollar-1 then 0: one0
braces ten: ten
after shift 3: first=four count=7

The set -- ... builtin loads ten positional parameters directly, which is handy for demonstrations and for resetting the argument list. $10 is parsed as $1 followed by the character 0, so it prints one0 -- the tenth parameter requires ${10}, which correctly prints ten. Then shift 3 drops the first three, so $1 becomes four and the count falls from ten to seven. The set -- form is also the idiomatic way to clear all positional parameters (set -- with nothing after it) or to replace them wholesale.


Real World Example: A Hand-Written Option Parser

Before reaching for getopts, it is worth writing one option parser by hand, because it shows exactly what shift is for. This parse function walks its arguments with a while-shift loop and a case: it accepts -n as a flag, -e as an option that takes a value, -- as the end-of-options marker, and treats everything else as a positional target.

#!/usr/bin/env bash
set -u

parse() {
  local dry=0 env="dev"
  local -a targets=()
  while (( $# > 0 )); do
    case $1 in
      -n)  dry=1; shift ;;
      -e)  env=$2; shift 2 ;;
      --)  shift; break ;;
      -*)  echo "unknown option: $1" >&2; return 2 ;;
      *)   targets+=( "$1" ); shift ;;
    esac
  done
  while (( $# > 0 )); do targets+=( "$1" ); shift; done
  echo "dry-run: $dry"
  echo "env:     $env"
  echo "targets: ${targets[*]}"
  echo "count:   ${#targets[@]}"
}

parse -n -e prod web1 web2 -- -weird-name

Output:

dry-run: 1
env:     prod
targets: web1 web2 -weird-name
count:   3

Trace the consumption. -n matches the flag case, sets dry to 1, and shifts one. -e matches the value case, copies $2 (prod) into env, and shifts two -- the option and its value together. web1 and web2 fall to the * case and are appended to the targets array. -- matches the end-of-options case, shifts past itself, and breaks the loop; the second loop then sweeps the remaining -weird-name into targets even though it starts with a dash, which is precisely what -- is for: it lets a target that looks like an option through unharmed. The result is a dry run against the prod environment with three targets.

The parser works for well-formed input but has real defects. First, -e with no following value is unguarded: calling parse -e with nothing after it makes env=$2 reference an unset parameter, which under set -u aborts the script with an unbound-variable error rather than a friendly message -- a robust parser checks (( $# >= 2 )) before consuming a value. Second, combined short flags are not supported: -ne is treated as a single unknown option and rejected, whereas users of Unix tools expect -ne to mean -n -e; splitting bundled flags is exactly the tedious work that getopts exists to do. Third, the option value is never validated -- -e banana is accepted as happily as -e prod, so a typo in the environment name sails through to be discovered only when the deployment targets the wrong place.


Common Mistakes

  1. Writing $10 for the tenth parameter. $10 is $1 immediately followed by a literal 0, not the tenth argument. Parameters from ten onward require braces: ${10}, ${11}. Forgetting this produces a value that looks almost right -- the first argument with a zero stuck on the end.
  1. Iterating over $@ unquoted. for a in $@ word-splits every argument on whitespace, so an argument containing a space is shattered into pieces. Always iterate with for a in "$@", quoted, to preserve each argument as one item.
  1. *Confusing "$@" with "$".** Quoted "$*" joins all arguments into a single word; quoted "$@" keeps them separate. Using "$*" in a loop runs the body once over one fused string, which is almost never intended when you meant to process each argument.
  1. Shifting past the end of the queue. shift with no parameters left returns non-zero and can warn. Guard argument-consuming loops with while (( $# > 0 )) so you never shift an empty list, especially under set -e where the non-zero status could abort the script.
  1. Reading an option's value without checking it exists. -e) value=$2; shift 2 assumes $2 is present; if the option was last on the line, $2 is empty or, under set -u, an error. Verify (( $# >= 2 )) before consuming a value argument.
  1. Assuming a function sees the script's arguments. Inside a function, $1 and $@ refer to the function's own arguments, not the script's. If a function needs the script-level arguments, pass them in explicitly, for example myfunc "$@" from the top level.
  1. Forgetting to handle the end-of-options marker. Without a -- case, a legitimate positional argument that begins with a dash, like a filename -weird-name, is misread as an unknown option. Support -- so users can pass dash-leading values.
  1. Losing arguments to an unquoted expansion in a call. Passing somecmd $@ unquoted re-splits arguments; passing somecmd "$@" forwards them exactly as received. Forwarding arguments to another command should almost always use the quoted form.
  1. Using shift to skip a value but forgetting the flag also shifts. For an option that takes a value you must shift 2 -- once for the flag and once for its value. Shifting only once leaves the value in the queue, where it is misread as the next option or target on the following iteration.

Best Practices

  • Always iterate arguments with quoted "$@". This single habit preserves arguments that contain spaces and is correct in every case where you want to process each argument in turn. Reserve "$*" for the rare time you deliberately want one joined string.
  • Guard shift loops with a count test. Write while (( $# > 0 )) around argument consumption so you never shift an empty queue. The count is the reliable signal that there is still work to do, and it keeps the loop safe under set -e.
  • Check that a value-taking option has its value. Before shift 2, verify (( $# >= 2 )) and emit a clear error on stderr if the value is missing. This turns a cryptic unbound-variable abort into an actionable message.
  • Use braces for parameters ten and above. Write ${10} and ${11} whenever a function or script can receive that many arguments. The brace form is unambiguous and costs nothing; relying on single-digit forms is a latent bug the day a caller passes a tenth argument.
  • Support the end-of-options marker. Include a -- case in hand-written parsers so callers can pass positional arguments that begin with a dash. It is a small addition that matches the behaviour users expect from standard tools.
  • Forward arguments with the quoted at-form. When one script or function must pass its arguments to another command, use "$@" so the arguments arrive intact. This is the idiomatic wrapper pattern and avoids re-splitting.
  • Copy positional parameters into named locals early. At the top of a function, assign local src=$1 dst=$2 so the rest of the body reads meaningful names and does not depend on the parameters staying in place after a shift. It also documents the expected argument order.
  • Prefer getopts for anything beyond a couple of flags. Hand-written parsers are instructive and fine for one or two options, but bundled flags, long options, and value validation quickly justify the standard getopts builtin covered in the next lesson.

Practice Exercises

  1. Boundary preservation. Write a function that is called with three arguments where two contain spaces, and print each argument on its own line first with quoted "$@" and then with unquoted $@. Show how many items each loop produces and explain in a comment why the unquoted form breaks the arguments apart.
  1. A shift-based queue walker. Write a function that consumes its arguments one at a time with shift, printing the current front and the remaining count each pass, and stops cleanly when the queue is empty. Confirm it never errors when called with zero arguments, and explain how the count guard achieves that.
  1. A safe value-taking option. Extend a small parser so that an option -o requires a following value, but add a guard that prints a clear error to stderr and returns non-zero when the value is missing. Demonstrate both the success case and the missing-value case, and contrast the error with what set -u alone would produce.
  1. Argument forwarding. Write an outer function that validates it received at least one argument, then forwards all of its arguments unchanged to an inner function using "$@". Pass an argument containing a space and show that it survives the hop intact, then show how dropping the quotes corrupts it.