Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
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.

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

$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.

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.

./backup.sh ~/code "old projects" weeklyStep 1 of 4
  1. Word 0

    ./backup.sh, so that is $0.

Drills

Answer fast — trust the rule.

quick drill

For ./backup.sh a b c, what is $#?

quick drill

For ./backup.sh ~/notes, what is $0?

quick drill

A script is run with ten arguments, one through ten. What does echo $10 print?

quick drill

For ./backup.sh "My Notes" daily, what is $1?

Remember

  • $0 is the script, $1 onward the arguments, $# counts them.
  • Number the words; quoted text counts as one word.
  • Trap: missing arguments are silently empty, and $10 is not the tenth; use ${10}.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainLet the caller choose the folder

Change backup.sh so it is called as ./backup.sh "My Notes" daily, taking the source folder from the first argument and a label from the second. Show the lines, say what $0, $1, $2 and $# hold for that call, and explain why the quotes around "$1" matter.