how to pass a named argument in a bash script

How to Pass a Named Argument in a Bash Script

In this article, you’ll learn how to pass a named argument in a bash script to get data into the script, and control the script for better automation and management. So, let’s get started!

Positional Arguments

Positional arguments in a bash script do not clearly define the data type an argument contains. However, you can use the meaningful option with named arguments to help the bash script understand the data stored in the arguments. That’s what we’ll be covering in this article.

How to Pass a Named Argument in a Bash Script

There are multiple ways to pass arguments in a bash script. The first method uses positional arguments, such as $1, $2, $3, and so on. Another method is to use the named arguments. In this guide, we’ll discuss the second method in detail. Continue reading to learn more about how to pass a named argument in a bash script.

Read a Named Argument Using Getopts

Getopts is a POSIX shell built-in command that retrieves options from a list of parameters. To use this utility, we’ll perform the steps discussed below.

First, open the terminal by pressing “Ctrl + Alt + T”. after that, create a bash file using the nano editor:

nano myScript.sh

Add the following content inside the script:

#!/bin/bash
while getopts "i:r:" var
do
   case "$var" in
       i) ID=${OPTARG};;
       r) GPA=${OPTARG};;
   esac
done
if [[ "$ID" == "34" ]]; then
    echo "You obtained $GPA"
elif [[ "$ID" == "90" ]]; then
    echo "You obtained $GPA"
else
    echo "ID is invalid."
fi

To elaborate, this script consists of getopts to parse the command-line arguments. It expects two options, -i for ID and -r for GPA. If the option is -i, the value is assigned to the ID variable.

If the option is -r, the value is assigned to the GPA variable.

To execute this script, type:

./myScript.sh -i 56 -r 3.8

The output should look like this:

pass a named argument in a bash script

If you don’t add the command-line arguments, you’ll get an error.

Pass a Named Argument in a Bash Script Using Getopt

Alternatively, you can also use the getopt command in the bash script to process long command-line arguments. For this method, modify the above bash script as shown below:

#!/bin/bash
format=$(getopt -n "$0" -l "id:,gpa:" -- -- "$@")
if [ $# -lt 3 ]; then
   echo "Wrong number of arguments are passed."
   exit
fi
eval set -- "$format"
while [ $# -gt 0 ]
do
     case "$1" in
          --id) Id="$2"; shift;;
          --gpa) Gpa="$2"; shift;;
          --) shift;;
     esac
     shift;
done
if [[ "$Id" == "90" && "$Gpa" == "3.8" ]]; then
    echo "$Id obtained $GPA"
else
    echo "Invalid user"
fi

The getopt function parses the long options --id and --gpa with their respective arguments. In addition, the if statement in the script checks the number of command-line arguments. If it is less than 3, it prints an error message and exits the script. 

Furthermore, we’ve also used the eval command that sets the positional parameters based on the parsed options. The loop iterates over the positional operators while the case statement checks the position parameters and performs actions accordingly. 

If the parameter is --id, the value is assigned to the Id variable, and the next positional parameter ($2) is skipped using shift. However, if the parameter is --gpa, the value is assigned to the Gpa variable, and the next positional parameter ($2) is skipped using shift.

Lastly, the script checks the value of the Id and Gpa variables. If the Id is equal to “90” and Gpa is equal to “3.8”, it prints a message indicating that the user with that ID obtained the GPA.

To properly execute the script, you’d type:

./script.sh --id 90 --gpa 3.8

Note that if you miss any arguments, you’ll get an error. For instance, if you type:

./script.sh --id 90

You’ll get the following error:

pass arguments using getopts

Use Keyword Arguments in a Bash Script

The third method you can use is keyword arguments. This method is useful in explaining the arguments to the users. Let’s look at its example:

if [[ $1 =~ ^(-f|--firstname) ]]
then
    firstname="$2"
fi
echo "My first name is $firstname"

In this script, we’ve used the keyword argument format to pass a named argument in a bash script. To elaborate, the if statement checks for the $1 argument to be -f or –firsname. If the condition is true, then it assigns the value to the firstname variable. 

Lastly, the script prints a message that includes the value of the firstname variable using the line echo "My first name is $firstname".

You must ensure that the first argument is either -f or –firstname, and the second argument is the actual argument that will be processed inside the script. To execute this script, type:

./script.sh -f John
./script.sh -firstname John

You should get a similar output:

use keyword arguments in bash script

In addition, it is also possible to add multiple named arguments. However, you’ll have to modify the script as shown below:

while [[ "$#" -gt 0 ]]
do case $1 in
    -f|--firstname) firstname="$2"
    shift;;
    -s|--secondname) secondname="$2"
    shift;;
    -a|--age) age=20;;
    *) echo "Unknown parameter passed: $1"
    exit 1;;
esac
shift
done
echo "My name is $firstname $secondname, age $age"

We’ve made 2 changes here:

  • Add a second keyword argument similar to the first one
  • Add a while loop to handle the arguments. 

Execute the following command to run this script:

 ./script.sh --firstname John -–secondname Smith
 ./script.sh --f John -–s Smith

Use Loop Constructs to Pass a Named Argument in Bash Script

Positional arguments are useful when passing the arguments. However, you can’t use them because you don’t know the exact number of arguments to pass in a bash script. In this scenario, we use the loop construct. 

In loop construct, we use a $@ variable, which is the array of all the input parameters. For example, we have a bash script that takes the username from the command line and prints it:

i=1;
for user in "$@" 
do
    echo "$user";
    i=$((i + 1));
done

To execute the script, type:

./script.sh john smith bill “sam” carol

And you’ll get a similar output:

pass a named argument using loop

Even though the size of the input is unknown, the loop iterates over the array and runs till the last argument. 

Bonus: Check Whether the Argument is Passed or Not

When passing arguments in a script during runtime, it is crucial to assign a default value to the variable and then overwrite it. 

In the example given below, we’ve first assigned the default arguments to the firstname and secondname variables. In addition, we’ve also used the $# variable to check if the number of arguments from the command is greater than zero or not. 

Lastly, we’ve overwritten the default values with the named arguments passed during the runtime.

For example:

firstname="Distroid"
secondname="Distroid2"
while [[ "$#" -gt 0 ]]
do case $1 in
    -f|--firstname) firstname="$2"
    shift;;
    -s|--secondname) secondname="$2"
    shift;;
    *) echo "Unknown parameter passed: $1"
    exit 1;;
esac
shift
done
echo "My name is $firstname $secondname"

To execute, type:

./script.sh -f Sidrah -s Abdullah

And you’ll get this output:

check number of arguments

Final Thoughts

In this guide, we’ve discussed different ways to pass a named argument in a bash script during runtime. Apart from positional parameters, you can use the loop constructs, keyword arguments, and getopt to pass named arguments in your script.

Learn more about how to use awk command, timeout command and conditional statements in a bash script.

If this guide helped you, please share it.

Related Posts