3 Methods to Pass Named Parameters in a Bash Script

Positional parameters are commonly used to pass the user arguments to a Bash script. However, merely numbers of positional parameters($1, $2, $3 etc.) without any additional information lacks the purpose of a particular argument. Named parameters, on the other hand, offer a more intuitive approach, providing clarity about the purpose of each argument. By using named parameters users can specify parameters by name rather than relying solely on their position in the command line. In this article, I will discuss various methods to pass named arguments in a Bash Script.

What is Named-Argument or Named-Parameter in Bash?

In Bash scripting, “named-parameter” refers to specific type of command-line arguments that are passed to a script as a key-value pair or flag-value pair format. For instance, a script may require a number for successful execution. While providing the number as an argument, users can provide it using a key-value pair format like this:

./script.sh num=20

Here, num is the key or flag, and 20 is the corresponding value. This format makes it easy to track the command line arguments by their name.

3 Methods to Pass Named Parameters in a Bash Script

It is easy to incorporate named arguments into a Bash script using a simple for loop and case statement. Additionally, specialized commands such as getopts or getopt can be utilized for parsing named parameters.

Down below, three different methods for passing named parameters in a Bash script are discussed-

Read the Comparative Analysis of Methods to pick the best one for your needs.

Method 01: Using Loop and Case Statement

A for loop along with a case statement is capable to parse named-arguments in Bash script. The following script utilizes those constuctions to pass named-arguments:

#!/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

The Bash script iterates through each argument passed to it. For each argument, it checks if it matches a specific pattern (name=*, age=*, gender=*) using a case statement. If it does, it extracts the value after the equal sign (=) using "${arg#*=}" and assigns it to the corresponding variables (name, age, gender). Finally, it prints out the values of these variables.

To see how it behaves, run the script with the following command:

./named_params.sh name=John age=20 gender=male

Passing named argument in Bash using loop and case statement (1)Upon execution of the script, it processes the named-arguments name, age, and gender and their respective values. For instance, 20 is provided as the value of the named-argument age. The output of the script accurately retrieves 20 as the value of age.

Method 02: Using the “getopts” Command

The getopts command is a Bash built-in that facilitates the parsing of command-line options and arguments. Using getopts, name of a parameter can be defined as a single-character option or flag. And the argument taken by the flag is treated as the value of the named-parameter. The value of the named-parameter can be easily extracted within script using the OPTARG variable. Follow the code given below to fully understand the usability of getopts to pass named-parameters:

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

echo "ID of ${Name} is ${ID}"
EXPLANATION

The script utilizes the getopts command to parse command-line options(named-parameters) and their corresponding values. It defines three options: -n, -i, and -r, which indicates Name, ID, and Result respectively. Inside the case statement, it assigns the value of named-argument to its corresponding variable using the special variable OPTARG. After parsing all options, it prints out the ID of the provided name.

Passing-named-argument-in-Bash-using-getopts-commandWhile executing the script, triggering the option -n saves the named-parameter Jhon to the variable Name. Similarly, it stores the 12020 in the ID variable and 4.6 in the Result variable. Finally, it uses those variables to print the id of the person.

Method 03: Using the “getopt” Command

To conviniently pass long form of named-parameter, use getopt command. Unlike getopts, getopt supports both long and short form of options. For instance, you can use –name, –age, and –gender or their corresponding short forms (-n, -a, -g), to provide specific values of those named-arguments. Following script demonstrate how getopt should be used to handle named-argument in Bash:

#!/bin/bash

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

# Set options for the getopt command
options=$(getopt -o "nag" -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 command-line, 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.

Passing-named-argument-in-Bash-using-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 shows the designated name Cathy”, age, 25, and the gender Female in the separate lines.

Comparative Analysis of the Methods

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

Methods Pros Cons
getopts
  • 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.
getopt
  • 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.
Loop with Case Statement
  • 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.

In simple terms, the way you choose to pass named-arguments 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 in the command line is more than enough.

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 to do named command line arguments in Bash Scripting?

To implement command line arguments either use getopts command or simple case statement with a loop construction. Moreover, you can use the getopt utility of parse named-parameter to Bash script.

How do I parse named parameter in Bash function?

In Bash, you can parse named parameters in a function using the getopts built-in command. Here’s a basic example of how to do it:

#!/bin/bash

# Define your function
my_function() {
    while getopts ":a:b:" opt; do
        case $opt in
            a) arg_a="$OPTARG";;
            b) arg_b="$OPTARG";;
            \?) echo "Invalid option: -$OPTARG" >&2;;
        esac
    done

    # Optional: Shift the parsed options so that $1 refers to the first non-option argument
    shift $((OPTIND -1))

    # Access the parsed arguments
    echo "Argument a: $arg_a"
    echo "Argument b: $arg_b"
    echo "Additional arguments: $@"
}

# Call the function with named parameters
my_function -a value_a -b value_b additional_argument1 additional_argument2

Can I pass named-parameter using case statement and while loop?

Yes. You can pass named-parameter using case statement with a while loop. The following example demonstrate this:

#!/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"

What is the difference between “getopts” and “getopt” in parsing named argument in Bash?

The getopts command is a Bash built-in that is used for parsing short options, typically single-character options like -a, -b, etc. It’s straightforward to use and suitable for simple command-line option parsing tasks. On the other hand, getopt is an external command usually provided by the GNU getopt package. It supports parsing both short and long options. If your script requires only basic option parsing with short options, getopts is usually sufficient, while getopt becomes handy for more advanced parsing needs, especially involving long options.

Related Articles


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

4/5 - (1 vote)
LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now
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.

1 thought on “3 Methods to Pass Named Parameters in a Bash Script”

Leave a Comment