Accessing Parameters

suggest change

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:

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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents