Command-Line Arguments: $0, $1, and More
A Bash script becomes far more useful when it can receive input from the person who runs it. The words you type after the script name are called command-line arguments, and Bash hands them to the script through a set of special variables: $0 for the script name, $1, $2, $3 and so on for the arguments themselves.
How Arguments Reach a Script
When you type a command, the shell reads the whole line, splits it into words, and starts the program with those words. For a script, the first word is the script name and every word after it is an argument:
./backup.sh notes.txt /mnt/usb
# ^ ^ ^
# $0 $1 $2
Inside the script, Bash stores each word in a numbered variable. These numbered variables are called positional parameters, because their meaning depends on the position of the word in the command line.
| Variable | Meaning |
|---|---|
$0 | The name used to run the script |
$1 | The first argument |
$2 | The second argument |
$3 ... $9 | The third to the ninth argument |
${10}, ${11} ... | The tenth and later arguments (braces are required) |
$# | The number of arguments, not counting $0 |
A First Example
The script below prints the script name, the first three arguments and the number of arguments:
cat > args.sh <<'EOF'
#!/usr/bin/env bash
echo "script name : $0"
echo "first : $1"
echo "second : $2"
echo "third : $3"
echo "count : $#"
EOF
chmod +x args.sh
./args.sh red green
script name : ./args.sh
first : red
second : green
third :
count : 2
Only two arguments were given, so $3 is empty. Bash does not report an error when you read an argument that was not supplied. It treats the variable like any unset variable and expands it to an empty string. The count $# is the reliable way to know how many arguments really arrived.
Run it again with four arguments:
bash args.sh red green blue yellow
script name : args.sh
first : red
second : green
third : blue
count : 4
The fourth argument, yellow, was counted by $# but not printed, because the script only prints $1 to $3.
What $0 Contains
$0 holds the script name exactly as it was typed on the command line, so it changes with the way you start the script:
| Command | Value of $0 |
|---|---|
./args.sh | ./args.sh |
bash args.sh | args.sh |
bash /home/ana/scripts/args.sh | /home/ana/scripts/args.sh |
A common use of $0 is a usage message that always shows the correct name. Because $0 can contain a whole path, remove everything up to the last slash with ${0##*/}. This expansion deletes the longest part of the value that matches */ from the front, which leaves only the file name:
cat > usage.sh <<'EOF'
#!/usr/bin/env bash
if [[ $# -lt 2 ]]; then
echo "Usage: ${0##*/} SOURCE DEST" >&2
exit 1
fi
echo "copy $1 to $2"
EOF
chmod +x usage.sh
./usage.sh a
echo "exit=$?"
./usage.sh a b
Usage: usage.sh SOURCE DEST
exit=1
copy a to b
The >&2 sends the usage message to standard error, where error messages belong. The script ends with exit 1 when fewer than two arguments are present, and continues normally when both are given.
Arguments Are Separated by Whitespace
Bash splits the command line on spaces. To pass a value that contains spaces as one argument, quote it:
./args.sh "New York" Paris
script name : ./args.sh
first : New York
second : Paris
third :
count : 2
Without the quotes, the shell sees three words:
./args.sh New York Paris
script name : ./args.sh
first : New
second : York
third : Paris
count : 3
The quotes are removed by the shell. The script receives New York, not the quote characters. Lesson 46 covers single and double quotes in more detail.
To see exactly what a script receives, including empty arguments and repeated spaces, use a small helper that prints every argument between square brackets:
cat > show.sh <<'EOF'
#!/usr/bin/env bash
echo "count: $#"
for a in "$@"; do echo "[$a]"; done
EOF
chmod +x show.sh
./show.sh "New York" Paris "" 'two spaces'
count: 4
[New York]
[Paris]
[]
[two spaces]
An explicitly empty argument ("") is still an argument: it is counted and it keeps its position. The loop for a in "$@" is explained in the next lesson. It walks through every argument, however many there are.
Arguments Beyond the Ninth
Without braces, Bash reads only one digit after the dollar sign. So $10 means the first argument followed by the character 0. Use braces for two-digit positions:
cat > ten.sh <<'EOF'
#!/usr/bin/env bash
echo "\$10 = $10"
echo "\${10} = ${10}"
EOF
bash ten.sh a b c d e f g h i j k
$10 = a0
${10} = j
$10 expanded to a0 ($1 is a, followed by a literal 0), while ${10} correctly picked the tenth argument, j. In practice, scripts with so many arguments usually process them in a loop (see the lessons on shift and getopts later in the tutorial).
Handling Missing Arguments
Reading an argument that was not provided gives an empty string. Combine that with $# and with default values to make a script robust:
cat > noargs.sh <<'EOF'
#!/usr/bin/env bash
echo "count=$#"
echo "first=[$1]"
echo "first with default=[${1:-nobody}]"
EOF
bash noargs.sh
count=0
first=[]
first with default=[nobody]
The expansion ${1:-nobody} means "use $1, but if it is unset or empty, use nobody". Lesson 45 explains this family of expansions. Here it lets a script supply a sensible value when an argument is left out:
cat > greet.sh <<'EOF'
#!/usr/bin/env bash
name=$1
greeting=${2:-Hello}
echo "$greeting, $name!"
EOF
bash greet.sh Ana
bash greet.sh Ana Welcome
Hello, Ana!
Welcome, Ana!
The first argument is the name, and the second is an optional greeting that defaults to Hello.
A missing argument can also break arithmetic, because an empty value leaves a gap in the expression:
cat > sum.sh <<'EOF'
#!/usr/bin/env bash
echo "sum: $(( $1 + $2 ))"
EOF
bash sum.sh 4 9
bash sum.sh 4
sum: 13
sum.sh: line 2: 4 + : syntax error: operand expected (error token is "+ ")
With only one argument, Bash evaluated 4 + and failed. Checking $# first, as usage.sh did, turns this confusing message into a clear one. Lesson 128 covers validating required arguments.
A script that expects at least one argument can also stop early with a useful message:
cat > count.sh <<'EOF'
#!/usr/bin/env bash
if [[ $# -eq 0 ]]; then
echo "No files given" >&2
exit 2
fi
echo "Checking $# file(s)"
for f in "$@"; do
[[ -e $f ]] && echo "found: $f" || echo "missing: $f"
done
EOF
touch real.txt
bash count.sh
echo "exit=$?"
bash count.sh real.txt ghost.txt
No files given
exit=2
Checking 2 file(s)
found: real.txt
missing: ghost.txt
The Shell Expands Patterns Before the Script Runs
Wildcards are expanded by the shell, not by the script. The script only sees the result:
touch a.txt b.txt c.txt
./show.sh *.txt
count: 3
[a.txt]
[b.txt]
[c.txt]
The script did not receive *.txt. It received the three file names that matched. This is why a command such as rm *.txt can work on many files even though rm itself knows nothing about wildcards.
Functions Have Their Own Arguments
A function receives its own $1, $2 and $#, separate from those of the script. Inside a function, $0 still holds the script name:
cat > fn.sh <<'EOF'
#!/usr/bin/env bash
show() { echo "in function: \$0=${0##*/} \$1=$1 \$#=$#"; }
echo "script: \$1=$1 \$#=$#"
show inner1 inner2 inner3
echo "script again: \$1=$1"
EOF
bash fn.sh outer
script: $1=outer $#=1
in function: $0=fn.sh $1=inner1 $#=3
script again: $1=outer
While the function ran, $1 meant inner1. As soon as it returned, $1 meant outer again. Lessons 88 and 89 explain functions and their arguments in depth.
Arguments with bash -c
You can also run a command string with bash -c. In this form, the first word after the string becomes $0, and the rest become $1, $2 and so on:
bash -c 'echo "name=$0 first=$1 second=$2"' mytool alpha beta
name=mytool first=alpha second=beta
This catches many people by surprise: the first extra word is not $1, it is the name that the shell will use for $0 (for example in error messages).
Arguments Are Not Standard Input
Arguments and input are two different channels. Text sent through a pipe goes to standard input, and a script does not see it as an argument:
echo hi | bash args.sh | head -1
script name : args.sh
The word hi did not become $1. The script has to read standard input with commands such as read (see lesson 31) if it wants that data.