Positional parameters and shift
What you need to know
Arguments passed to a script become positional parameters. $0 is the script name as invoked (or shell name in some invocation modes); $1 and $2 are its first two arguments; $# counts arguments without $0. Use ${10} for the tenth, because $10 expands $1 followed by literal 0. shift removes the first positional parameter and renumbers the rest. As standalone quoted command arguments, "$@" preserves each argument separately (zero words when there are no arguments); "$*" joins them into one word. IFS is the shell variable controlling field separation: the join uses its first character, a space if IFS is unset, or no separator if IFS is empty. The next chapters explain splitting in depth.
Run each example separately as a new Bash script (Chapter 1). Tested with Bash 5.2.37 on Debian 13, default shell options; no personal configuration is required.
Read script arguments
bash -c 'printf "name=%s count=%s\n" "$0" "$#"; printf "first=%s second=%s\n" "$1" "$2"' demo 'New York' reportExpected stdout:
name=demo count=2first=New York second=reportFor bash -c, the first argument after the command string becomes $0, so demo is not counted. For a file, run bash script.sh with arguments after the filename.
Forward separate arguments
bash -c 'printf "<%s>\n" "$@"; printf "joined=<%s>\n" "$*"' demo 'New York' '' reportExpected stdout:
<New York><><report>joined=<New York report>With default IFS, the separate empty argument produces an empty pair of angle brackets. The joined form has two spaces between York and report. With zero arguments, "$@" expands to zero words, but printf with no data arguments still formats an empty string.
Shift after consuming an argument
bash -c 'printf "%s\n" "$1" && shift && printf "next=%s count=%s\n" "$1" "$#"' demo alpha beta gammaExpected stdout:
alphanext=beta count=2After a successful shift, beta becomes $1. The && chain skips the final report if shift fails. If there are not enough parameters for the requested shift, it fails; check the count before shifting in real scripts.
Common mistakes
Do not use unquoted $@ to forward arguments: spaces and wildcard characters can change the argument list. Use "$@". Handle a missing argument deliberately; ${1-} is a safe empty fallback for an unset first parameter.
Practice
Run a script with three arguments including New York and an empty string. Print the count, print each using quoted $@, then shift once and print the new count.
Next lesson: Words, tokens and shell operators