Skip to the workspace
Pebellslearn by building
Arguments and String Manipulation  ›  Lesson

Positional Arguments: $0, $1 and $#

$1, $2, $3 12 minA 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.

shell bash / Positional Arguments: $0, $1 and $#

Explore each scene at your own pace.

01 · The rule

The rule

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

$0 is the script, $1 onward the arguments, $# counts them.

For the call

./backup.sh "My Notes" daily

the 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, $2 is empty, not an error.
  • From the tenth on, you need braces: ${10}. Plain $10 means $1 followed by the character 0.
  • $0 is handy in messages, so a usage line always shows the name the script was actually called by.
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.