Positional Arguments: $0, $1 and $#
backup.sh still has src="$HOME/notes" written inside it. To back up a different folder you must edit the file. Real tools take their input from the command line instead: ./backup.sh ~/code. Bash hands every script the words that followed its name.
The rule
$0is the script,$1onward the arguments,$#counts them.
For the call
./backup.sh "My Notes" dailythe script sees:
| Parameter | Value |
|---|---|
$0 |
./backup.sh (the name used to run it) |
$1 |
My Notes |
$2 |
daily |
$# |
2 |
The caller's quotes made My Notes a single argument, and the script must keep it whole with its own quotes:
src="$1"
label="$2"
echo "$(basename "$0"): backing up $src as $label"Details worth knowing:
- These are called positional parameters: their names are their positions.
- A missing argument is simply empty, like an unset variable. With only one argument,
$2is empty, not an error. - From the tenth on, you need braces:
${10}. Plain$10means$1followed by the character0. $0is handy in messages, so a usage line always shows the name the script was actually called by.
The shortcut
Number the words. Write the command line out, put 0 under the script name and 1, 2, 3 under each argument, treating anything in quotes as one word. $# is the last number.
Word 0
./backup.sh, so that is$0.
Drills
Answer fast — trust the rule.
For ./backup.sh a b c, what is $#?
For ./backup.sh ~/notes, what is $0?
A script is run with ten arguments, one through ten. What does echo $10 print?
For ./backup.sh "My Notes" daily, what is $1?
Remember
$0is the script,$1onward the arguments,$#counts them.- Number the words; quoted text counts as one word.
- Trap: missing arguments are silently empty, and
$10is not the tenth; use${10}.
