getopts is a very convenient bash script utility, which helps you to conveniently and gracefully handle the passing of flags(short version), and arguments in a clean, standardized manner. Instead of having the developer manually handle the flags passed to a script, this provides a handy way of handling this when iterating through a while loop.
Prerequisites: It is recommended to have a basic idea of the following topics:
- Basic Understanding of bash script.
- Flags in bash.
- Arguments in bash.
getopts optstring name [arg]
To get the syntax through terminal:
Working with getopts command
1. Printing the help section: Enter the following command to print the help section of the getopts command.
The above command will print the details of the command along with some parameters and options that could be used to run the command.
2. Usage in a script: getopts could be used in a script in Linux as well. The following script depicts the same.
#!/bin/bash while getopts ":a:bc:" flag;do echo "flag -$flag, Argument $OPTARG"; done
This script runs a while loop, which iterates through the arguments that match with given optstring, in this case, “a:bc:”, and stores the value of the flag in the variable flag. If the flag had any associated argument, it is stored in a variable OPTARG.
The optstring works in the following way:
- For every option letter, getopts stores the option in the variable flag(declared just after the optstring), and iterates the loop.
- Every option letter followed by a colon expects an argument, which is stored in the variable OPTARG.
- If getopts was expecting an argument, but could not parse one, it prints an error. If it was not expecting one, OPTARG will be initialized to “”(an empty string).
- If the very first character of the optstring was “:”(a colon), the error message is not printed
3. Running the script by passing the arguments as expected.
./getoptsDemo.sh -a argA -b
Note: OPTARG for -b is blank, and not its previous value since it is initialized for every iteration. Also, -c is not passed, which is not an issue, as each flag in optstring is optional.
4. Running the script by skipping the parameter for a flag where it is required: This prints an error message. The flag is initialized to “?”, and OPTARG is “.
5. Running the script by adding a flag not present in the optstring: This prints an error message. Again, the flag is initialized to “?”, and OPTARG is “”.
If the first character was “:”, getopts goes into silent mode, the error messages are not printed, and the behavior changes in some cases. Consider the optstring “:a” for the following example-
6. Skipping the parameter for a flag where it is required: The flag is initialized to “:”, and OPTARG is set to the option character.