Parsing Parameters in Bash Scripts [5 Examples]

LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now

Parsing and passing arguments into bash or shell script is mostly similar to how we provide arguments to functions within Bash scripts. In this article, I will look through different examples of processes to parse parameters in bash scripts. So Let’s start.

Key Takeaways

  • Understanding the concept of parsing parameters in bash script.
  • Get familiar with parsing parameters without using the positional parameters.

Free Downloads

What is Parameters Parsing in Bash Script?

Parameter parsing in Bash script refers to the process of extracting and interpreting input values, known as parameters or arguments, provided to a script when it is executed. These parameters can be passed to the script either when running it from the command line or within the script itself. The script then uses these parsed parameters to perform specific actions or make decisions based on the provided input. Let’s look at the code given below. The objective is to do an arithmetic summation between two numbers.

#!/bin/bash

x=$1
y=$2
result=$((x + y))
echo "The sum of the two given numbers is: $result"

What is Parameters Parsing in Bash ScriptHere as the picture depicts, the intended numbers which are referred to as the bash arguments are passing by means of the command line. Those values are then linked with the code with positional parameters such as $1, $2, etc. So this is an example of parameters parsing in a bash script.

5 Practical Examples of Parsing Parameters in Bash Scripts

Bash scripts often require inputs or options from users, and parameter parsing is essential for retrieving these values and making decisions based on them. There are plenty of ways you can parse your arguments depending on the requirement of data you need to pass. Here I am going to discuss five different examples to illustrate the idea. Don’t forget to practice by yourself and make one or two codes on your own.

Example 01: Assigning Command Line Arguments With Bash Parameters

In Bash, you can access commandline arguments passed to a script or program using variables like $1, $2, and so on. These variables allow you to capture and manipulate input values provided when the script is executed. Follow the following bash script to understand the concept.

Steps to Follow >

❶ At first, launch an Ubuntu Terminal.

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

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

❸ Copy the script mentioned below:

#!/bin/bash

echo "The 1st given Parameter = $1 "
echo "The 2nd given Parameter = $2 "
EXPLANATION

This Bash script, denoted by the shebang #!/bin/bash, is a simple script that takes command-line arguments and prints them. The echo command is used to display the values of the first and second commandline parameters, which are accessed using $1 and $2, respectively.

❹ 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 parsing_parameters.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.
  • parsing_parameters.sh: File name.

❻ Run the script by the following command:

./parsing_parameters.sh 3 6

Assigning Command Line Arguments with Bash ParametersWhen I run this script with arguments 3 and 6, it displays the values of these parameters, making it a basic way to assign command-line arguments.

Example 02: Parsing Bash Parameters Without Using Positional Parameters

Instead of relying solely on positional parameters $1, $2, and so on, you can use for loop to handle the bash argument as many as you want. Here’s a brief example:

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

Script (parsing_parameters1.sh) >

#!/bin/bash

# Counter for parameter position
count=1

# Loop through all positional parameters
for arg in "$@"; do
    echo "The $count parameter is: $arg"
    ((count++))
done
EXPLANATION

This Bash script initializes a counter variable count and uses a for loop to iterate through all the arguments provided when the script is executed. Inside the loop, it echoes the position of the current argument using $count and its corresponding value using $arg. The counter count is incremented with each iteration, providing a sequential enumeration. This script is useful for displaying and processing all commandline arguments without using the positional parameters.

Use the following code to run the script in your command line.

./parsing_parameters1.sh Hello 56 LinuxSimply World

Assign the Parsing Arguments to the Bash VariableUpon execution, the bash script successfully returns each argument’s value and states its positional number.

Example 03: Assign the Parsing Arguments to the Bash Variable

You can assign the parsed arguments to the bash variable and redirect it to the algorithm. Let’s say you want to take two positional arguments as your input data and do some arithmetic multiplication. See the code given below to understand the concept of it.

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

Script (assigning_value.sh) >

#!/bin/bash

num1=$1
num2=$2
product=$(($num1*$num2))
echo "The product of $num1 and $num2 is = $product"
EXPLANATION

This Bash script takes two command-line arguments, $1 and $2, assigns them to variables num1 and num2, respectively, calculates their product using $(($num1*$num2)), and then echoes the result, displaying “The product of $num1 and $num2 is = $product“.

Use the following code to run the bash script.

./assigning_value.sh 4 5

Parsing Short Command-Line Options with the getopts Command in Bash ScriptUpon execution, the code returns “The product of 4 and 5 is = 20” as the output of the given code.

Example 04: Parsing Short Command-Line Options With the “getopts” Command in Bash Script

You can use the getopts command in a Bash script to parse short command-line options. getopts is a built-in tool in Bash for this purpose. Here’s an example of how to use getopts to parse short options:

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

Script (short_command.sh) >

#!/bin/bash

# Initialize variables with default values
option_a=false
option_b=false

# Usage function
usage() {
  echo "Usage: $0 [-a] [-b]"
  echo "  -a: Enable option A"
  echo "  -b: Enable option B"
  exit 1
}

# Parse options using getopts
while getopts "ab" opt; do
  case $opt in
    a)
      option_a=true
      ;;
    b)
      option_b=true
      ;;
    \?)
      echo "Invalid option: -$OPTARG"
      usage
      ;;
  esac
done

# Shift to the next positional parameter (if any)
shift $((OPTIND-1))

# Main script logic
echo "Option A: $option_a"
echo "Option B: $option_b"
EXPLANATION

This Bash script initializes two variables, option_a and option_b, with default values set to false. It defines a usage function that provides instructions on how to use the script’s options. The script then uses the getopts command to parse short commandline options, specifically -a and -b, toggling the corresponding variables when these options are provided.

If an invalid option is detected, it displays an error message and invokes the usage function. After parsing options, it uses shift to remove processed options from the list of positional parameters and finally displays the values of option_a and option_b to show whether the options were enabled or not.

Use the following code to run the bash script.

./short_command.sh
./short_command.sh -a
./short_command.sh -ab

Parsing Short Command-Line Options with the getopts Command in Bash Script

As the image depicts above, the script ./short_command.sh accepts command-line options -a and -b. When run without any options, both option_a and option_b are set to false by default. When invoked with the -a option, option_a is set to true, while option_b remains false. Similarly, when both -a and -b options are provided, both option_a and option_b are set to true.

Example 05: Parsing Long Command-Line Options With the “getopt” Command in Bash Script

To parse long command-line options (also known as flags or switches) in a Bash script, you can use the getopt command. Here’s an example of how to use getopt to parse long options:

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

Script (long_command.sh) >

#!/bin/bash

# Initialize variables with default values
option_a=false
option_b=false

# Usage function
usage() {
  echo "Usage: $0 [--option-a] [--option-b]"
  echo "  --option-a: Enable option A"
  echo "  --option-b: Enable option B"
  exit 1
}

# Parse options using getopt
TEMP=$(getopt -o '' --long option-a,option-b -- "$@")

if [ $? -ne 0 ]; then
  usage
fi

eval set -- "$TEMP"

# Loop through the options and arguments
while true; do
  case "$1" in
    --option-a)
      option_a=true
      shift
      ;;
    --option-b)
      option_b=true
      shift
      ;;
    --)
      shift
      break
      ;;
    *)
      echo "Invalid option: $1"
      usage
      ;;
  esac
done

# Main script logic
echo "Option A: $option_a"
echo "Option B: $option_b"
EXPLANATION

This Bash script is designed to handle long commandline options, specifically –option-a and –option-b. It starts by initializing two variables, option_a and option_b, to false as default values. The script defines a usage function to display usage instructions. It then utilizes the getopt command to parse the long options, –option-a and –option-b.

If getopt encounters any issues (indicated by a nonzero exit code). The script employs a while loop to process options and arguments, setting variables accordingly and shifting the arguments as needed. Finally, it outputs the values of option_a and option_b to indicate whether these options were enabled or not.

Use the following code to run the bash script.

./long_command.sh
./long_command.sh --option-a
./long_command.sh --option-a --option-b

 Parsing Long Command-Line Options with the getopt Command in Bash ScriptThe script ./long_command.sh is designed to accept long options –option-a and –option-b. When executed without any options, both option_a and option_b are set to false by default. If inserted with the –option-a flag, option_a is set to true, while option_b remains false. Similarly, when both –option-a and –option-b flags are provided, both option_a and option_b are set to true.

Conclusion

In conclusion, parsing parameters in Bash scripts is crucial for handling command-line inputs effectively. By using techniques like positional parameters, scripts can receive and process arguments, making them more interactive and versatile. In this article, I have provided 5 different examples to give you an understanding of the subject matter. However, If you have any questions or queries regarding the article, feel free to comment below. I am one click away from interacting with you. Thank You.

People Also Ask

What is the difference between $* and $@?

$* treats all command-line arguments as a single string, while $@ treats each argument as a separate entity, preserving their individuality. This distinction is crucial when working with arguments that contain spaces or special characters in Bash scripts.

How to read arguments from command-line in bash?
To read command-line arguments in Bash, utilize positional parameters like $1, $2, etc., for unnamed arguments. For named options and arguments, employ the getopts command to provide structured parsing and handling capabilities in your script.
What is difference between $* and $#?
$* represents all command-line arguments as a single string, while $# signifies the count of arguments provided. $# helps determine how many arguments were passed, while $* treats them as a whole.
What is the difference between $[] and $() in Bash?

${} is used for variable expansion and manipulation, while $() is used for command substitution, executing a command, and using its output as a value.

Related Articles


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

4.9/5 - (15 votes)
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