BASH Programming

How to Get Arguments with Flags in Bash

Bash is a widely used shell and command language used in Unix and Linux systems. It provides various ways to pass arguments to shell scripts, including using flags to pass optional arguments, this article, will discuss how to get arguments with flags in Bash.

Getting Arguments with Flags in Bash

To get arguments with flags in Bash, you can use the “getopts” command. The “getopts” command is a built-in function in Bash that can be used to parse command-line options and arguments. It takes three arguments: the option string, the variable to store the current option, and the name of the variable to store the remaining arguments. Here’s an example:

#!/bin/bash

while getopts ":x:y:" opt; do

case $opt in

x)

arg1="$OPTARG"

;;

y)

arg2="$OPTARG"

;;

\?)

echo "Invalid: -$OPTARG" >&2

;;

:)

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

;;

esac

done

shift $((OPTIND-1))

echo "Argument 1: $arg1"

echo "Argument 2: $arg2"

Here the “getopts” command is used to parse the command-line options “-x” and “-y”. The “:” character after each option indicates that the option requires an argument and the variable “opt” stores the current option, and the variables “arg1” and “arg2” store the corresponding arguments.

The “case” statement is used to handle each option so if the option is “x”, the argument is stored in “arg1”. If the option is “y”, the argument is stored in “arg2”.An error message is shown when an invalid option is given, as well as when no argument is given even if an option calls for one.

The OPTARG is used to store the value of the argument that is passed with the options -x or -y, while OPTIND-1 is used to shift the positional parameters to exclude the options and their arguments, leaving only the non-option arguments.

After parsing the options, the “shift” command is used to remove the options from the argument list. This ensures that the remaining arguments are stored in the correct variable.To use the script with flags, you can run the script with the flag options and arguments, like this:

./<script-name> -<flag1> <argument1> -<flag2> <argument2>

Conclusion

Using flags to pass optional arguments to Bash scripts can make scripts more flexible and powerful and with the “getopts” command, you can easily parse arguments and command-line options. By following the example in this article, you can implement flags in your own Bash scripts and handle them with ease.

About the author

Aaliyan Javaid

I am an electrical engineer and a technical blogger. My keen interest in embedded systems has led me to write and share my knowledge about them.