Glossary

Positional Parameters

Positional parameters are the arguments passed to a shell script or function, accessed through the special variables $1`, `$2, $3, and so on. Several related variables expose information about them:

  • $0: the name of the script (or shell)
  • $1, $2, ...: individual arguments
  • $#: number of arguments
  • **$@**: all arguments as separate words (use `"$@"` to preserve spacing)
  • $*: all arguments as a single word, joined by the first char of IFS
  • $$: the shell's PID
  • $?: exit code of the last command
  • $!: PID of the last background job
#!/bin/bash
echo "script: $0"
echo "args: $#"
echo "first: $1"
for arg in "$@"; do
  echo "got: $arg"
done

The distinction between "$@"` and `"$*" matters: the former expands to each argument as a separate word, preserving spaces within arguments, while the latter flattens them into one. Always use "$@" in loops, unless you have a specific reason not to. The shift builtin drops the first positional parameter, shifting the rest down, which is useful for parsing options.

Related terms: Shell Script, bash

Discussed in:

Also defined in: Textbook of Linux

Textbook of Linux — Learn Linux on iPhone — Download on the App Store