positional parameters
The numbered variables $1, $2 and so on that hold the arguments given to a script or function, with $# holding how many there are.
In more detail
Check $# before reading $1, and quote them as "$1" so an argument with spaces stays whole. Arguments past the ninth need braces, as in ${10}. At the prompt, set -- a b c replaces them so you can practise.
Examples
bash greet.sh Ada Graceecho "first: $1, count: $#"Related terms
- dollar at — The special parameter $@, which in double quotes expands to every argument, or array element with ${arr[@]}, as a separate word.
- dollar star — The special parameter $*, which in double quotes joins every argument into one word separated by a space.
- shift builtin — The builtin that drops $1 and moves every remaining positional parameter down by one, lowering $# as well.
- command-line argument — A word given to a command after its name, such as the file names in cp a.txt b.txt.
- dollar zero — The special parameter $0, which holds the name the current shell or script was started as.
Taught in
- Help, History, Completion And Aliases — Bash Scripting & Command Line Automation
- What Bash Does To A Line Before It Runs It — Bash Scripting & Command Line Automation
- Arrays, And Why Dollar At Is Not Dollar Star — Bash Scripting & Command Line Automation
- Reshaping Text: cut, sort, uniq, tr, sed, awk — Bash Scripting & Command Line Automation
- Exit Codes, And What Success Means — Bash Scripting & Command Line Automation
- Functions, local And declare — Bash Scripting & Command Line Automation
- Arguments: Dollar One, Dollar At, shift — Bash Scripting & Command Line Automation
- Option Parsing With getopts — Bash Scripting & Command Line Automation
- Debugging: set -x, bash -n And Reading The Error — Bash Scripting & Command Line Automation
- Style That Prevents Bugs — Bash Scripting & Command Line Automation
- eval, And What To Use Instead — Bash Scripting & Command Line Automation
- Scheduling, Monitoring And A Script That Reports — Bash Scripting & Command Line Automation