Taking Command Line Arguments in Bash

Overview

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.

#!/bin/bash
# print_args.sh
echo "You provided the arguments:" "[email protected]"

# You could pass all arguments to another program like this
# myProgram "[email protected]"

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.

#!/bin/bash
echo "You provided $# arguments"

Accessing a specific argument by index

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

#!/bin/bash
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.

#!/bin/bash
for arg in "[email protected]"
do
    echo "$arg"
done

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:

#!/bin/bash
for arg in "[email protected]"
do
    if [ "$arg" == "--help" ] || [ "$arg" == "-h" ]
    then
        echo "Help argument detected."
    fi
done

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

Conclusion

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

# All arguments
[email protected]

# Number of arguments
$#

# Specific arguments
$0
$1
$2

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