4 Methods to Pass Named Parameters in a Bash Script

As you may know, the positional parameters are used to pass the user arguments to the bash code. However, The effectiveness of positional parameters is limited as it can become unclear which argument corresponds to which data type. On the other hand, named parameters offer a more meaningful option, allowing a precise understanding of the data each argument represents. In this article, I will discuss various methods to pass named parameters in bash script.

Key Takeaways

  • Getting familiar with getopts and getopt commands to pass named arguments.
  • Understanding the usability of keyword arguments in named parameters.

Free Downloads

The “getopts” and the “getopt” Commands in Linux

The getopts command is a built-in feature of the Bash shell that facilitates the parsing of command-line options and arguments. It allows scripts to handle singlecharacter options (flags) provided by users when running the script.

Unlike the built-in getopts command in Bash, another command getopt offers more advanced options parsing capabilities, including support for both short options (single-character flags) and long options (multi-character flags). To learn how to incorporate those commands in named parameters, read the following method I am going to describe below.

4 Methods to Pass Named Parameters in a Bash Script

Down below, I am going to provide four different ways to pass named parameters in a bash script. Don’t forget to run those codes on your machine and share your thoughts in the comment section.

You can read our Comparative Analysis of Methods to distinguish between these four methods and pick the best one for your needs.

Method 01: Passing the Named Parameters Using the “getopts” Command

In this first method, I will discuss the named parameters using the getopts command. Passing named parameters using getopts in Bash is like giving your script special instructions through little flags you add when running it. These flags are usually just one letter, like -f for file. Follow the code given below to understand its usability fully.

Steps to Follow >

❶ At first, launch an Ubuntu terminal.

❷ Write the following command to open a file in Nano:

nano getopts.sh
EXPLANATION
  • nano: Opens a file in the Nano text editor.
  • getopts.sh: Name of the file.

❸ Copy the script mentioned below:

#!/bin/bash
# Read options and corresponding values
while getopts "i:r:" option; do
   case "$option" in
       i) StudentID=${OPTARG};;
       r) Result=${OPTARG};;
   esac
done

# Display message based on provided StudentID
if [[ "$StudentID" == "56" ]]; then
    echo "John Obtained GPA $Result out of 5.00"
elif [[ "$StudentID" == "34" ]]; then
    echo "Mark Obtained GPA $Result out of 5.00"
else
    echo "Invalid ID."
fi
EXPLANATION

The Bash script uses the getopts command to read named options and their corresponding values. The script iterates through the options (-i for StudentID and -r for Result) and assigns the values to variables (StudentID and Result). It then utilizes a conditional structure to display a message based on the provided StudentID.

If the StudentID matches 56, the script outputs “John Obtained GPA” followed by the provided Result out of 5.00. Similarly, if the StudentID is 34, it displays “Mark Obtained GPA” with the provided Result. If neither of these conditions is met, it outputs “Invalid ID.” This script allows customized messages based on the given StudentID and Result values.

❹ Press CTRL+O and ENTER to save the file; CTRL+X to exit.

❺ Use the following command to make the file executable:

chmod u+x getopts.sh
EXPLANATION
  • chmod: Changes the permissions of files and directories.
  • u+x: Here, u refers to the “user” or the owner of the file and +x specifies the permission being added, in this case, the “execute” permission. When u+x is added to the file permissions, it grants the user (owner) permission to execute (run) the file.
  • getopts.sh: File name.

❻ Run the script by the following command:

./getopts.sh -i 56 -r 4.23
EXPLANATION
  • /getopts.sh: File’s name.
  • -i: Refers to 56 as the StudentID.
  • -r: Refers to the Result corresponding to the StudentID.

Passing the Named Parameters Using the getopts CommandUpon providing the abovementioned command, the script interprets the provided StudentID 56 and Result 4.23 and then generates a message indicating that “John obtained a GPA of 4.23 out of 5.00.”

Method 02: Passing the Named Parameters Using the “getopt” Command

Following the previous method, you can also use the getpost command to pass the named parameters in a bash script. The getopt command effectively manages and processes named parameters. However, unlike the getsopt command which can only able to take short options, getopt command can deal with both long as well as short options. For instance, by defining options such as –name, –age, and –gender, the script allows users to provide specific values as input arguments.

You can follow the steps of Method 01, to save & make the script executable.

Script (getopt.sh) >

#!/bin/bash

# Initialize variables with default values
Name=""
Age=""
Gender=""

# Set options for the getopt command
options=$(getopt -o "" -l "name:,age:,gender:" -- "$@")
if [ $? -ne 0 ]; then
    echo "Invalid arguments."
    exit 1
fi
eval set -- "$options"

# Read the named argument values
while [ $# -gt 0 ]; do
    case "$1" in
        --name) Name="$2"; shift;;
        --age) Age="$2"; shift;;
        --gender) Gender="$2"; shift;;
        --) shift;;
    esac
    shift
done

# Display the provided information
echo "Name: $Name"
echo "Age: $Age"
echo "Gender: $Gender"
EXPLANATION

The Bash script begins by initializing three variables, namely Name, Age, and Gender. Initially, each variable contains empty values. Then, the script employs the getopt command to configure options for the commandline, allowing named parameters to be specified such as –name, –age, and –gender. The script checks if the exit status of the previous command (through $?) is not equal to zero, indicating an invalid argument setup. If that happens, it leads to an error message display and an exit code of 1.

Then the options are processed using eval set — “$options”, preparing for the named parameter values to be read. Through a while loop, the script parses through the provided arguments. In a case construct, the script looks for specific option patterns (–name, –age, and –gender), assigning their corresponding values to the variables Name, Age, and Gender via shift. The shift command moves the script’s argument pointer. The loop continues until all arguments are processed. Finally, the script outputs the gathered information, displaying the provided name, age, and gender values using the echo command.

Now run the script using the following command.

bash getopt.sh --name “Cathy” --age 25 --gender “Female”

Passing the Named Parameters Using the getopt CommandAs the image depicts above, the command line bash getopt.sh –name “Cathy” –age 25 –gender “Female” provides a structured presentation of the given input values using named parameters. The output command line shows the designated name Cathy”, age, 25, and the gender Female within the separate line.

Method 03: Read the Named Argument Without Using the “getopts” and the “getopt” Command

Reading named arguments in a Bash script without using getopts or getopt can involve manually passing the command-line arguments. Here’s an example of how you might achieve this:

You can follow the steps of Method 01, to save & make the script executable.

Script (without_getopt.sh) >

#!/bin/bash

# Loop through arguments
for arg in "$@"; do
    case "$arg" in
        --name=*) Name="${arg#*=}" ;;
        --age=*) Age="${arg#*=}" ;;
        --gender=*) Gender="${arg#*=}" ;;
    esac
done

# Display provided information
echo "Name: $Name"
echo "Age: $Age"
echo "Gender: $Gender"
EXPLANATION

In this Bash script, named parameters are read without utilizing the getopts or getopt command. The script iterates through the command-line arguments using a for loop. Within the loop, it employs a case statement to identify named argument patterns such as –name=, –age=, and –gender=. The values associated with these arguments are extracted using parameter substitution and then assigned to respective variables (Name, Age, and Gender). After processing the arguments, the script displays the gathered information, presenting the provided name, age, and gender values using the echo command.

Copy and paste the following command to run the script in your distribution.

./without_getopt.sh --name="Alice" --age="25" --gender="Female"

Read the Named Argument without Using the getopts and the getopt CommandUpon execution of the script, it processes the named parameters –name, –age, and –gender along with their respective values. It then outputs the provided name, age, and gender such as Name: Alice Age: 25 Gender: Female respectively.

Method 04: Use Keyword Arguments to Pass a Named Parameter in a Bash Script

Another approach you can utilize involves keyword arguments. This technique proves beneficial for passing the arguments to users. To illustrate, let’s delve into an example:

You can follow the steps of Method 01, to save & make the script executable.

Script (keyword_arguments.sh) >

#!/bin/bash

# Loop through the provided arguments
while [[ "$#" -gt 0 ]]; do
    case $1 in
        -f|--first) first_name="$2" # Store the first name argument
            shift;;
        -s|--last) last_name="$2" # Store the last name argument
            shift;;
        -a|--age) age=20;; # Set the default age value
        *) echo "Unknown parameter passed: $1" # Display error for unknown parameter
            exit 1;; # Exit the script with an error code
    esac
    shift # Move to the next argument
done

# Display the collected information
echo "Full name: $first_name $last_name, Age: $age"
EXPLANATION

The provided Bash script processes keyword arguments using a while loop and case statements. It accepts options like -f or –first for the first name, -s or –last for the last name, and -a or –age for the age (defaulted to 20). The loop iterates through the arguments, assigning values to corresponding variables. If an unrecognized option is encountered, an error is displayed and the script exits. Lastly, the code displays the values of the first name, last name, and default age using the echo command.

Execute the following command to run the script.

./keyword_arguments.sh -f John -s Doe -a

 Use Keyword Arguments to Pass a Named Parameter in a Bash ScriptThe command runs the script with the first name John and the last name Doe. You can also add the -a flag to set the age to the default value of 20.

Comparative Analysis of the Methods

Here’s a table outlining the pros and cons of the four methods for passing named parameters in a Bash script:

Methods Pros Cons
Method 1
  • Built-in Bash feature for handling options.
  • Standardized approach.
  • Handles short options.
  • Supports error handling.
  • Limited to singlecharacter short options.
  • Requires manual argument parsing for non-option arguments.
  • More complex syntax.
Method 2
  • Supports short and long options.
  • More flexible than getopts in handling complex scenarios.
  • Not a builtin Bash feature (requires external tool).
  • Still requires manual argument parsing for non-option arguments.
  • Less consistent syntax across platforms.
Method 3
  • Simple and intuitive for a small number of arguments.
  • No special parsing logic is needed.
  • Minimal syntax.
  • Limited to positional arguments.
  • Lacks standardized error handling.
  • Can become cumbersome with multiple arguments.
Method 4
  • Clear and readable method.
  • Self-explanatory argument names.
  • Enhanced script documentation.
  • Can handle any number of arguments.
  • Requires custom argument parsing logic.
  • Not built-in, needs manual implementation.
  • More verbose for a large number of arguments.

In simple terms, the way you choose to pass special names to your Bash script depends on how complicated your script is and what you care about most. If your script is basic and only needs a few choices, just directly mentioning the names is enough.

But if your script is complex, Method 1 is a good middle ground. It’s built into Bash and gives you a nice mix of built-in help and features. If you need to do some really fancy things with your choices and you’re okay with using an extra tool, then Method 2 can be really useful. However, if you want to avoid both Method 1 and 2, you can follow Method 3 to accomplish the same result.

Lastly, if making your code super easy to read and understand is your main goal, then using Method 4 to clearly explain what they do might be the way to go. It might take a bit more work, but it can pay off with easier-to-understand code.

Conclusion

In this article, I have tried to provide an overall demonstration of passing named parameters in a bash script using four different methods. I hope this will aid you in learning the bash script more. However, If you have any questions or queries, don’t forget to comment below. Thank you!

People Also Ask

How do I pass a keyword argument to a bash script?
You can pass keyword arguments to a Bash script using named parameters in the form of flags followed by values. For example: ./script.sh –key1=value1 –key2=value2
How do I pass multiple variables to a bash script?
To pass multiple variables to a Bash script, include them as space-separated values after the script’s name in the command line, like ./script.sh var1 var2 var3. The script can access these variables using positional parameters ($1, $2, $3, etc.).
What is $# in shell script?
In a shell script, $# signifies the count of commandline arguments supplied when the script is run. It helps in determining how many arguments have been passed to the script.
What is $1 and $2 in shell script?
 In shell scripting, $1 and $2 refer to the first and second positional arguments, respectively. They allow to access the input values directly within the script’s code.

Related Articles


<< Go Back to Parameters in Bash Scripting | Bash Scripting Tutorial

Rate this post
Mohammad Shah Miran

Hey, I'm Mohammad Shah Miran, previously worked as a VBA and Excel Content Developer at SOFTEKO, and for now working as a Linux Content Developer Executive in LinuxSimply Project. I completed my graduation from Bangladesh University of Engineering and Technology (BUET). As a part of my job, i communicate with Linux operating system, without letting the GUI to intervene and try to pass it to our audience.

Leave a Comment