Taking Command Line Arguments in Bash


Bash scripts are commonly used to perform a variety of tasks. These examples describe various ways you can work with command line arguments.

Pass arguments through to another program

Bash scripts are often used as wrappers to launch another application. A common task is to pass the command line arguments from the script to the program being loaded. Here is an example of passing all the arguments provided as-is.

# print_args.sh
echo "You provided the arguments:" "$@"

# You could pass all arguments to another program like this
# myProgram "$@"

Ensure the script has the executable permission, and run it with a few arguments passed.

chmod +x print_args.sh
./print_args.sh 1 2 3

Get the number of arguments passed

The number of arguments passed is stored in the $# variable.

echo "You provided $# arguments"

Accessing a specific argument by index

You can access a specific argument by its index like this:

echo "Arg 0: $0"
echo "Arg 1: $1"
echo "Arg 2: $2"

Argument 0 is the name of the script being invoked itself.

Iterating through each argument

This example shows how to iterate through each argument one-by-one, and print out the value.

for arg in "$@"
    echo "$arg"

Check arguments for specific value

If you wanted to iterate through each argument and check if one equals a specific value, you can do that with the following:

for arg in "$@"
    if [ "$arg" == "--help" ] || [ "$arg" == "-h" ]
        echo "Help argument detected."

Then try running that while passing it a -h or --help flag.


Did you notice a trend in the variables? All of the command line argument variables started with a dollar sign $.

# All arguments

# Number of arguments

# Specific arguments

With this knowledge, you should be able to work with the command line arguments provided to a bash script.