Linux Commands

Command Line Arguments

In many cases, bash scripts require argument values to provide input options to the script. You can handle command-line arguments in a bash script in two ways. One is by using argument variables, and another is by using the getopts function. How you can handle command-line arguments is shown in this tutorial.

Using argument variables:

The argument variable starts from $0. The main script file name is stored in $0, which receives argument values from command line arguments. If two arguments are passed in the command-line, then sequentially, the argument values will be received in $1 and $2 variables.

Example -1: Sending three numeric values in the command line arguments

Create a bash file with the following script. The script will receive three-argument values and store them in $1, $2, and $3 variables. It will count the total number of arguments and print argument values using a loop without a loop. The sum of all argument values will be printed later.

#!/bin/bash
# Counting total number of arguments
echo "Total number of arguments: $#"

# Reading argument values individually
echo "First argument value : $1"
echo "Second argument value : $2"
echo "Third argument value : $3"

# Reading argument values using loop
for argval in "$@"
do
       echo -n "$argval "
done

# Adding argument values
sum=$(($1+$2+$3))

# print the result
echo -e "\nResult of sum = $sum"

The following output will appear after executing the script file with three numeric argument values, 50, 35, and 15.

$ bash cmdline1.sh 50 35 15

Example -2: Taking filename as an argument

Create a bash file with the following script to count the total number of characters of any file. Here, the filename will be passed as a command-line argument.

#!/bin/bash
filename=$1
totalchar=`wc -c $filename`
echo "Total number of characters are $totalchar"

Run the bash script with the filename as a single argument value and run another command to check that file’s total number of characters. Here, the weekday.txt file is used as an argument value. The total number of characters in the weekday.txt file is 57.

$ bash cmdline2.sh weekday.txt
$ wc -c weekday.txt

Using getopts function:

If you want to store data in the database or any file or create a report in a particular format based on command line arguments values, then the getopts function is the best option to do the task. It is a built-in Linux function. So, you can easily use this function in your script to read formatted data from the command line.

Example -3: Reading arguments by getopts function

Create a bash file with the following script to understand the use of the getopts function. ‘getopts’ function is used with a while loop to read command-line argument options and argument values. Here, 4 options are used which are ‘i’, ‘n’, ‘m’ and ‘e’. the case statement is used to match the particular option and store the argument value in a variable. Finally, print the values of the variable.

#!/bin/bash
while getopts ":i:n:m:e:" arg; do
    case $arg in
        i) ID=$OPTARG;;
        n) Name=$OPTARG;;
        m) Manufacturing_date=$OPTARG;;
        e) Expire_date=$OPTARG;;
    esac
done
echo -e "\n$ID $Name $Manufacturing_date $Expire_date\n"

Run the file with the following options and argument values. Here, p100 is the value of -i option, ‘Hot Cake‘ is the value of -n option, ‘01-01-2021‘ is the value of -m option and ‘06-01-2021‘ is the value of -e option.

$ bash cmdline3.sh -i p001 -n 'Hot Cake' -m '01-01-2021' -e '06-01-2021'

When you need to send simple values in a script, then it is better to use argument variables. But if you want to send data in a formatted way, it is better to use the getopts function to retrieve argument values. The uses of both argument variables and getopts options have shown in the next example.

Example-4: Reading normal arguments and arguments with getopts options

The ways to read command-line arguments using argument variables and getopts options have been shown separately in previous examples of this tutorial. But these two ways can be used in a single script to read command-line argument values. Create a bash script with the following code to read the command line argument values passed by getopts options and argument parameters. Here, three getopts options have been used to read the command line’s hostname, username, and password. Next, shift command has been used to remove all getopts options from the command for reading the command line values using argument variables. This script will read and print a maximum of three values of the argument variables. If no argument value without option will be given after executing the code, then a message will be printed; otherwise, the values of the argument variable will be printed.

#!/bin/bash

# Reading arguments with getopts options
while getopts 'h:u:p:' OPTION; do
    case "$OPTION" in
        h)
            # Print hostname
            echo "The host name is $OPTARG" ;;
        u)
            # Print username
            echo "The username is $OPTARG" ;;
        p)
            # Print password
            echo "The password is $OPTARG" ;;
        *)
            # Print helping message for providing wrong options
            echo "Usage: $0 [-h value] [-u value] [-p value]" >&2
            # Terminate from the script
            exit 1 ;;
    esac
done

# Remove all options passed by getopts options
shift "$(($OPTIND -1))"

# Reading first normal arguments
if [ ! -z $1 ]; then
    echo "The first table name is $1"
else
    echo "No normal argument is given."
    exit 1
fi

# Reading second normal arguments
if [ ! -z $2 ]; then
    echo "The second table name is $2"
fi

# Reading third normal arguments
if [ ! -z $3 ]; then
    echo "The third table name is $3"
fi

The following output will appear if the wrong option is given at the time of executing the code. Here, option -a does not exist in the script.

The following output will appear if the valid options with the values are given in the command line at the time of executing the code.

The following output will appear if the valid options and normal argument values are used in the command line at the time of executing the code. Here, the normal arguments are customer and employee.

Using ‘$@’ for reading command-line arguments:

The command-line arguments can be read without using argument variables or getopts options. Using ‘$@‘ with the first bracket is another way to read all command-line argument values.

Example-5: Reading command line argument values without variable

Create a bash file with the following script to read the argument values without any argument variable and calculate the sum of three command line argument values. “$@” has been used with the first brackets here to read all argument values into an array. Next, the sum of the first three array values will be printed.

#!/bin/bash
# Read all arguments values
argvals=("$@")
# Check the total number of arguments
if [ $# -gt 2 ]
then
    # Calculate the sum of three command line arguments
    sum=$((${argvals[0]}+${argvals[1]}+${argvals[2]}))
    echo "The sum of 3 command line arguments is $sum"
fi

The following output will appear after executing the above script for the argument values 12, 20, and 90. The sum of these numbers is 122.

Conclusion:

The ways to provide command-line argument values without any option and with options have shown here. The way to read command-line argument values without using variables has shown here also. I hope this tutorial will help the readers to use command-line argument values properly in their bash script.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.