How to Get Arguments with Flags in Bash


Bash, the default shell for most Unix-based operating systems, provides a powerful set of tools and functionalities for automating tasks and managing system resources. One of the essential features of Bash is the ability to pass arguments to scripts or commands through the use of flags.

Flags enable you to customize and control the behavior of your scripts, making them more versatile and efficient. In this article, we will explore the art of working with arguments and flags in Bash, guiding you through the process step by step.

Getting Arguments with Flags in Bash

If you want to retrieve arguments with flags in Bash, you have the option to utilize the “getopts” command. This command is an inherent function in Bash that enables you to parse command-line options and arguments effectively. When using “getopts,” you need to provide three arguments: the option string, the variable to hold the current option, and the variable name for storing the remaining arguments. Consider the following example to better understand its implementation:

#!/bin/bash

while getopts ":a:b:" opt; do

 case $opt in

 a)

 first_arg="$OPTARG"

 ;;

 b)

 second_arg="$OPTARG"

 ;;

 \?)

 echo "Invalid: -$OPTARG" >&2

 ;;

 :)

 echo "Option -$OPTARG requires an argument." >&2

 ;;

 esac

done

shift $((OPTIND-1))

echo "First Argument : $first_arg"

echo "Second Argument : $second_arg"

The code starts by defining a while loop with the “getopts” command, followed by a colon (:) to specify the available options, in this case, “a” and “b”. Inside the loop, the script utilizes the “case” statement to handle each option accordingly.

If the script encounters the “-a” flag, it assigns the value of the corresponding argument to the variable “first_arg”. Similarly, if the “-b” flag is encountered, the script assigns the argument value to the variable “second_arg”. If an invalid option is provided, the script outputs an error message indicating the invalid flag. If an option requires an argument, but none is provided, the script displays an error message specifying the missing argument.

After parsing all the options, the script uses the “shift” command to remove the processed options from the command-line arguments. Finally, it outputs the values of “first_arg” and “second_arg” to demonstrate the successful retrieval of the provided arguments with flags.

sudo bash<name-of-script-file> -<flag1> <first-argument> -<flag2> <second-argument>

 

A screenshot of a computer Description automatically generated

Conclusion

Utilizing flags to pass optional arguments to Bash scripts can greatly enhance their flexibility and functionality. With the “getopts” command, parsing command-line options and arguments becomes a seamless process. By referring to the example presented in this article, you can effortlessly incorporate flags into your own Bash scripts and effectively manage them.

Print Friendly, PDF & Email
Categories