4 Methods to Pass Named Parameters in a Bash Script

4 Methods to Pass Named Parameters in a Bash Script:

4 Methods to Pass Named Parameters in a Bash Script, The positional parameters are what the bash code utilizes, as you may know, to pass the user arguments. Positional parameters can be limited in their effectiveness, though, as it can become unclear which argument belongs to which data type. Named parameters, on the other hand, provide a more useful choice by enabling a detailed comprehension of the data each argument represents. I’ll go over a few different ways to pass named arguments in a bash script in this article.

Key Takeaways

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

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

The built-in getopts command in the Bash shell makes it easier to parse arguments and options from the command line. When a script is executed, it enables scripts to handle single-character options (flags) supplied by users.

A different command, getopt, has more sophisticated options parsing capabilities than the built-in getopts command in Bash. It can support both short options, which are single-character flags, and long options, which are multi-character flags. Go through the procedure I’ll provide below to find out how to include those instructions in named parameters.

4 Methods to Pass Named Parameters in a Bash Script

In this post, I’ll outline four methods for passing named parameters to a bash script. Remember to execute those codes on your computer and leave a comment with your ideas.

To choose the most appropriate way for your requirements, compare these four approaches and read our Comparative Analysis of Methods.

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

I’ll talk about the named parameters in this first technique by utilizing the getopts command. It’s similar to providing your script specific instructions through small flags you add when running it to pass named arguments using getopts in Bash. Usually, there is simply one letter in these options, such as -f for file. To properly grasp its usability, follow the code provided below.

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 getopts command is used by the Bash script to read named options and their associated values. The script allocates the values to the variables (StudentID and Result) by iterating through the parameters (-i for StudentID and -r for Result). After that, it makes use of a conditional structure to show a message in accordance with the supplied StudentID.

❹ 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

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

To pass the named arguments in a bash script, you can alternatively use the getpost command, which works similarly to the previous technique. Named parameters are efficiently managed and processed by the getopt command. But the getopt command can handle both long and short options, in contrast to the getsopt command, which can only handle short options. For instance, the script enables users to supply particular values as input parameters by specifying options like –name, –age, and –gender.

To save and make the script executable, you can adhere to Method 01’s instructions.

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

Name, Age, and Gender are the first three variables that the Bash script initializes. Every variable starts off with empty values. The script then uses the getopt command to set up options for the command-line, enabling named parameters like name, age, and gender to be given. The script determines whether the preceding command’s exit status (via $?) is equal to zero, indicating an improper argument configuration. If it occurs, an error message and an exit code of 1 are displayed.

Now run the script using the following command.

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

As 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”, age25, and the gender Female within the separate line.

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

In order to read named arguments in a Bash script without utilizing getopts or getopt, the command-line arguments may need to be explicitly passed. Here’s an illustration of how you could do it:

To save and make the script executable, you can adhere to Method 01’s instructions.

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

Named parameters are read in this Bash script without using the getopts or getopt command. The script uses a for loop to run over the command-line inputs. To recognize named parameter patterns like –name=, –age=, and –gender=, the loop uses a case statement. Using parameter substitution, the values related to these arguments are extracted and subsequently assigned to the appropriate variables (Name, Age, and Gender). The script uses the echo command to display the name, age, and gender values that have been provided after processing the arguments.

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

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

Upon execution of the script, it processes the named parameters –name, –age, and –gender along with their respective values. It then outputs the provided nameage, 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

There is also the option to use keyword arguments. This method works well for giving users access to the arguments. Let’s look at an example to better understand this:

To save and make the script executable, you can adhere to Method 01’s instructions.

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 given Bash script uses case statements and a while loop to handle keyword parameters. It takes the following formats: -f for first name, -s for last name, and -a or age for age (defaults to 20). As iterating through the arguments, the loop gives values to the appropriate variables. In the event that an unidentified option is found, the script terminates and an error message appears. Finally, the code uses the echo command to show the values for the first name, last name, and default age.

Execute the following command to run the script.

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

The 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.
2 method
  • Supports short and long options.
  • More flexible than getopts in handling complex scenarios.
  • Not a builtin Bash feature (requires external tool).
  • Less consistent syntax across platforms.
3 method
  • 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.
4 method
  • 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.

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!

Leave a Reply

Your email address will not be published. Required fields are marked *