How to Use Positional Parameters in Bash Scripts

While user-defined variables provide a means for script authors to create containers to store values used by a script, Bash also provides some predefined variables, which can be useful when writing shell scripts. One type of predefined variable is positional parameters.

Positional parameters

Positional parameters are variables which store the values of command-line arguments to a script. The variables are named numerically. The variable 0 refers to the script name itself. Following that, the variable 1 is predefined with the first argument to the script as its value, the variable 2 contains the second argument, and so on. The values can be referenced with the syntax $1, $2, etc.

Bash provides special variables to refer to positional parameters: $* and $@. Both of these variables refer to all arguments in a script, but with a slight difference. When $* is used, all of the arguments are seen as a single word. However, when $@ is used, each argument is seen as a separate word. This is demonstrated in the following example.

$ cat showargs
#!/bin/bash

for ARG in "$*"; do
    echo $ARG
done
$ ./showargs "argument 1" 2 "argument 3"
argument 1 2 argument 3
$ cat showargs
#!/bin/bash

for ARG in "$@"; do
    echo $ARG
done
$ ./showargs "argument 1" 2 "argument 3"
argument 1
2
argument 3

Another value that may be useful when working with positional parameters is $#, which represents the number of command-line arguments passed to a script. This value can be used to verify whether any arguments or the correct number of arguments, are passed to a script.

$ cat countargs
#!/bin/bash
echo "There are $# arguments."
$ ./countargs
There are 0 arguments.
$ ./countargs "argument 1" 2 "argument 3"
There are 3 arguments.