🎓 A1Learner
🔍
0 of 47 lessons completed

Bash Script Arguments

Script arguments are the words typed after the script name when a script runs. Bash stores those words in numbered variables called positional parameters.

Read the first two arguments

The words after the script name fill $1 and $2 in order. This run uses bash main.sh apple banana.

echo $1
echo $2

Count and list all arguments

The variable $# counts the arguments given. The variable $@ expands to all of them, as this run with apple banana shows.

echo $#
echo $@

Read the script name with $0

The variable $0 holds the name used to run the script. Running bash main.sh makes $0 print main.sh.

echo $0
echo $1

Example

echo "Script: $0"
echo "First: $1"
echo "Second: $2"
echo "Count: $#"
echo "All: $@"

Key points

  • A positional parameter is a numbered variable that holds one script argument.
  • The variable $1 holds the first argument and $2 holds the second.
  • The variable $# holds the count of arguments given.
  • The variable $@ holds all the arguments together.
  • The variable $0 holds the name the script was run with.
  • Running bash main.sh apple banana gives $1 as apple and $2 as banana.

In this example, the script runs as bash main.sh apple banana. The first echo prints $0, which is the script name main.sh. The next two echoes print $1 and $2, the words apple and banana. The fourth echo prints $#, the count of two arguments. The last echo prints $@, which holds both arguments together.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

A script runs as bash main.sh red blue. What does $2 hold?