The getopts (get options) is a built-in command Bash shell. The OPTARG variable in Bash is one of the few special variables of getopts. Its purpose is to store command line arguments passed under an option. This article aims to show you how OPTARG works and its practical usage in Bash scripting.
What is OPTARG in Bash?
OPTARG is a shell variable in Bash that takes the value of the current option’s argument when using the getopts command. When a script parses command-line options using getopts, it iterates through each option specified by the user and assigns the corresponding argument (if any) to OPTARG.
How Does OPTARG Work?
To have a clear understanding of OPTARG, you must understand the functions of the getopts command. The getopts command is utilized for parsing command-line options and arguments. The syntax of the command is as follows:
getopts optstring variable_name [arg]
For every option letter specified in the optstring, getopts assigns the currently processed option to the variable declared immediately after the optstring. For example:
getopts "ui" flag
Here, the optstring is “ui”, when iterating over the optstring using a while loop, the variable flag
can take the value u or i or both depending upon what user provides when executing the script. Look at a full-fledged Bash script demonstrating this:
#!/bin/bash
while getopts "ui" flag; do
echo $flag
done
During the first execution, when the option -u is provided, the variable flag takes the value ‘u’. However, when both -u and -i options are provided, the value of the variable flag first becomes ‘u’ and then ‘i’. Additionally, when no options are provided, the variable flag is null, and the script doesn’t show anything. This behavior is acceptable because in getopts options are not mandatory to provide.
OPTARG in the getopts Command
If a letter of optstring is followed by a colon, the option is expected to have an argument. For instance, for the optstring “u:i”, if the ‘u’ option is triggered then it is mandatory to provide an argument. This argument should be separated from the option/flag by a space. See the command below:
getopts "u:i" flag
Here comes the OPTARG variable. By default, the argument provided after the option is stored in the OPTARG variable. When iterating over the optstring using a while loop, a case statement facilitates redirecting the execution path of the script depending on the options. Here is how it works:
#!/bin/bash
while getopts "u:i" flag; do
case ${flag} in
u )
echo "Option -u specified with argument: $OPTARG"
;;
i )
echo "Option -i is triggered"
;;
esac
done
The Bash script utilizes a while loop along with the getopts command to parse command-line options. It specifies two options, ‘-u’ which requires an argument, and ‘-i’ which does not.
Inside the loop, a case statement is used to check the currently processed option. If the ‘-u’ option is encountered, it prints a message indicating the option along with its argument accessed through the $OPTARG
variable. If the ‘-i’ option is encountered, it prints a message indicating that the ‘-i’ option was triggered.
When option ‘-u’ is triggered without any argument the script shows a message “option requires an argument”. But it works fine when an argument “Anita” is given after triggering the option ‘-u’.
3 Practical Usage of OPTARG in Bash Scripting
The OPTARG variable can be useful for multiple purposes. One can employ it to handle multiple options. Moreover, it can be used to control verbosity mode. Most importantly it is easy to show error messages regarding invalid options utilizing OPTARG. The following three examples are excerpted from numerous real-world usage of OPTARG:
Example 1: Handling Multiple Optional Arguments
The OPTARG variable is useful for handling multiple optional arguments. For instance, if there are two flags, and each takes an argument, then OPTARG can be used to assign each of those arguments to variables for further processing. Here is an example:
#!/bin/bash
while getopts "f:o:h" flag; do
case ${flag} in
f)
input_file=${OPTARG}
echo "The input file is ${input_file}"
;;
o)
output_file=${OPTARG}
echo "The output file is ${output_file}"
;;
h)
echo "Usage: ./multiplearg.sh -f input_file -o output_file"
exit 0
;;
esac
done
This Bash script utilizes a while loop and the getopts command to parse command-line arguments. It accepts three options: -f
for specifying an input file, -o
for specifying an output file, and -h
for displaying usage information.
Inside the loop, the case statement handles each option -f and -o, and stores the corresponding filenames in variables using OPTARG. If triggered, the third option -h displays a usage message and exits.
From the above image, file1.txt and file2.txt are parsed as arguments of -f and -o options respectively. The OPTARG variable successfully retrieves the arguments as shown in the image.
Example 2: Controlling Verbosity
A Bash script may or may not process long and short-form options simultaneously. By controlling verbosity one can enable or disable the ability of processing long and short-form options at a time. To control verbosity using OPTARG, initialize a variable “verbose” to 0 that indicates verbosity is off. Then utilize getopts to parse an option -v for verbosity, which can take an argument. If triggered with argument say- 1, verbosity is turned on. The following script demonstrates the idea:
#!/bin/bash
verbose=0
while getopts "v:" flag
do
case ${flag} in
v) verbose=${OPTARG}
echo "Verbose mode activated."
;;
esac
done
This Bash script sets up a variable named “verbose” with a value of 0 to indicate verbosity is off. The getopts command processes an option -v
option which can take an argument. When the -v option is encountered, the script updates the “verbose” variable using OPTARG. Finally, it displays a message confirming the activation of verbose mode.
While executing the script the -v option is triggered with argument 1. Therefore, the program shows that “Verbose mode activated”.
Example 3: Indicating Invalid Options Invalid Option
The getopts command processes a single option on each iteration of the associated while loop. If an option is not recognized (based on the option string), getopts returns a ‘?’ (question mark). In this case, the OPTARG variable holds the invalid option character. This is handy to guide users about the invalid option. Here is an example:
#!/bin/bash
while getopts "ab" flag; do
case ${flag} in
a)
echo "Option -a is triggered."
;;
b)
echo "Option -b is triggered."
;;
?)
echo "Invalid option found: -${OPTARG}."
exit 1
;;
esac
done
This Bash script processes command-line options using the getopts command. It specifically looks for the options ‘a’ and ‘b’. If either option ‘a’ or ‘b’ is found, it prints a corresponding message. If an invalid option is encountered, the script displays an error message indicating the invalid option using the ${OPTARG}
and then exits with an error code of 1.
Executing the program with -a option perfectly works. However, when -k option is added which is not specified in the optstring of the getopts command, it prints that “Invalid option: -k”
Practice Problem on Bash OPTARG Variable
Create a Bash script image_resizer.sh that allows a user to provide three options:
- Option -d specifying the directory containing the images to be resized. It takes a pathname as an argument. Use OPTARG to print the path.
- The option -w specifying the desired width in pixels for the resized images. Use OPTARG to print the width of the resized images.
- And, option -h specifying the desired height in pixels for the resized images. Use OPTARG to print the height of the resized images.
- Finally, test your script by executing it with the following command:
./image_resizer.sh -d ./photos -w 800 -h 600
Conclusion
In conclusion, the OPTARG variable provides a valuable mechanism for processing command-line arguments. It allows you to handle both single and multiple arguments associated with options. Additionally, you can use OPTARG to inform users about invalid options. I hope this discussion has clarified the basics of using OPTARG effectively.
People Also Ask
What does OPTARG mean in Bash scripting?
OPTARG is a variable of getopts command that stores the value of the option argument found by getopts. While using getopts, after passing options with arguments, you can use OPTARG to access the arguments (if any) provided for those options.
Why is OPTARG null?
The OPTARG variable may remain null due to multiple reasons. First of all, if a command-line option doesn’t require an additional argument, OPTARG will naturally be NULL. For example, an option like -h (for help) typically stands alone. Another reason could be a missing colon in the optstring of the getopt command. The option string should include a colon (:) after option letters that expect arguments. For the optstring “ab:”, ‘b’ takes an argument. If you miss the colon after the letter ‘b’, OPTARG will be NULL even if you provide an argument.
What does a leading colon (:) signify in the getopt optstring?
A leading colon at the beginning of the optstring of the getopt command enables the silent mode of error reporting. This means that if a user provides an invalid option, getopt won’t print an error message by default. For example, consider the optstring “ab:c”. Here, options ‘a’, ‘b’, and ‘c’ are valid; ‘b’ requires an argument. On the other hand, optstring “:ab:c” is the same thing except the leading colon which enables errors for invalid options to be handled silently.
What does OPTIND do in the getopts command?
Like OPTARG, OPTIND is a special variable of the getopts command that contains the index of the next argument to be processed. OPTIND is initialized to 1 when the script starts and increases by 1 each time getopts is called and processes an option.
Related Articles
- How to Check Number of Arguments in Bash? [3 Methods]
- How to Use First Argument in Bash Script [5 Cases]
- How to Get Argument in Bash? [4 Methods]
- How to Pass Arguments to Bash Script? [5 Methods]
- How to Parse Optional Arguments in Bash Script [2 Ways]
- How to Pass Array as an Argument in Bash Function? [3 Ways]
- How to Set Default Argument in Bash [2 Methods]
- How to Use “getopts” in Bash [Complete Guide]
- [Solved] “bash: Argument list too long” Error
<< Go Back to Argument in Bash Script | Bash Functions | Bash Scripting Tutorial
FUNDAMENTALS A Complete Guide for Beginners