Positional Arguments: $0, $1 and $#
A script receives the words after its name as positional parameters $1, $2 and so on, with $0 holding the script's own name and $# the number of arguments.
Inspect the script name, argument count and individual positional arguments.
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.