Bash Accessing Parameters


Example

When executing a Bash script, parameters passed into the script are named in accordance to their position: $1 is the name of the first parameter, $2 is the name of the second parameter, and so on.

A missing parameter simply evaluates to an empty string. Checking for the existence of a parameter can be done as follows:

if [ -z "$1" ]; then
    echo "No argument supplied"
fi

Getting all the parameters

$@ and $* are ways of interacting with all the script parameters. Referencing the Bash man page, we see that:

  • $*: Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, it expands to a single word with the value of each parameter separated by the first character of the IFS special variable.
  • $@: Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, each parameter expands to a separate word.

Getting the number of parameters

$# gets the number of parameters passed into a script. A typical use case would be to check if the appropriate number of arguments are passed:

if [ $# -eq 0 ]; then
    echo "No arguments supplied"
fi

Example 1

Loop through all arguments and check if they are files:

for item in "$@"
do  
    if [[ -f $item ]]; then
        echo "$item is a file"
    fi  
done

Example 2

Loop through all arguments and check if they are files:

for (( i = 1; i <= $#; ++ i ))
do
    item=${@:$i:1}

    if [[ -f $item ]]; then
        echo "$item is a file"
    fi  
done