Shell script developers often leverage getopts, which is a bash script utility, to provide details around the shell script arguments. It provides a beautiful way in which you can specify details about your arguments to a user and a good way of parsing them for your program. It works analogously to the options available with other Linux commands. For example, -t -n can be used with the ls command .
Let us understand the getopts command with the help of examples in this blog post. For the first example, we will cover all the steps from scratch, including the creation of a script file, providing executable permissions to the script file, and then running it. For the later examples, we will only cover examples and not the steps to write a script file and execute it.
How do getopts Works?
We can understand this by going through the help text. To run the help command on getopts, please enter the below command:
getopts --help
Output
getopts: getopts optstring name [arg ...]
Parse option arguments.
Getopts is used by shell procedures to parse positional parameters as options.
OPTSTRING contains the option letters to be recognized; if a letter is followed by a colon, the option is expected to have an argument, which should be separated from it by white space.
Each time it is invoked, getopts will place the next option in the shell variable $name, initializing name if it does not exist, and the index of the next argument to be processed into the shell variable OPTIND. OPTIND is initialized to 1 each time the shell or a shell script is invoked. When an option requires an argument, getopts places that argument into the shell variable OPTARG.
getopts reports errors in one of two ways. If the first character of OPTSTRING is a colon, getopts uses silent error reporting. In this mode, no error messages are printed. If an invalid option is seen, getopts places the option character found into OPTARG. If a required argument is not found, getopts places a ':' into NAME and sets OPTARG to the option character found. If getopts is not in silent mode, and an invalid option is seen, getopts places '?' into NAME and unsets OPTARG. If a required argument is not found, a '?' is placed in NAME, OPTARG is unset, and a diagnostic message is printed.
If the shell variable OPTERR has the value 0, getopts disables the printing of error messages, even if the first character of OPTSTRING is not a colon. OPTERR has the value 1 by default.
Getopts normally parses the positional parameters, but if arguments are supplied as ARG values, they are parsed instead.
Exit Status:
Returns success if an option is found; fails if the end of options is encountered or an error occurs.
From the above output, we get the syntax of getopts which looks like the below :
getopts: getopts optstring name [arg ...]
Writing our First Shell Script file using getOpts
The following is a step-by-step guide on writing the first shell script file using getOpts:
1. To write a shell script, the file extension should be filename.sh file and you can create it using various commands, including vi or touch.
vi getOptExample1.sh
The above command will open the vi editor . To start writing code into the file, we need to press the “i” key to enter insert mode.
getOptExample1.sh
echo "This is demo example to use getOpt"
echo "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
echo " USAGE "
echo "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
echo "Available options to provide arguments: "
echo "-a : Represent first optional argument to the script"
echo "-b : Represent second optional argument to the script"
echo "-c: Represent third argument to the script"
while getopts 'abc:' OPTION; do
case "$OPTION" in
a)
echo "a represents the first argument"
;;
b)
echo "b represent second option argument which can be passed"
;;
c)
avalue="$OPTARG"
echo "The value provided is $OPTARG"
;;
?)
echo "script usage: $(basename \$0) [-a] [-b] [-c somevalue]" >&2
exit 1
;;
esac
done
2. After we have completed writing our shell script program, do the following:
|
|
exit | ESC + :q |
3. The next step is to provide executable permissions to our script. To provide that, we can execute the below command:
chmod 777 getOptExample1.sh
4. Now, we are ready to execute the above file. We can execute it using the below examples:
Output1: Calling script without argument
Run the following command to get the output:
$ sh getOptExample1.sh
Output
This is demo example to use getOpt
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
USAGE
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
Available options to provide arguments:
-a : Represent first optional argument to the script
-b : Represent second optional argument to the script
-c: Represent third argument to the script
Here in the above example, no option argument was passed, so the while loop did not execute.
Output2: Passing option argument
Run the following command to get the output:
$ sh getOptExample1.sh -a
Output
This is demo example to use getOpt
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
USAGE
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
Available options to provide arguments:
-a : Represent first optional argument to the script
-b : Represent second optional argument to the script
-c: Represent third argument to the script
a represents the first argument
In the above example, one option argument is passed, which leads to the execution of the match case during parsing of the option arguments and hence printed the result.
Output3: Passing multiple option argument
Run the following command to get the output:
$ sh getOptExample1.sh -ba
Output
This is demo example to use getOpt
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
USAGE
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
Available options to provide arguments:
-a : Represent first optional argument to the script
-b : Represent second optional argument to the script
-c: Represent third argument to the script
b represent second option argument which can be passed
a represents the first argument
Execution completed
In the above example, the options passed as an argument to the script executed in the order in which they were provided as input.
Output4: Passing option argument that expects a value(option argument postfixed with “:”)
Run the following command to get the output:
$ sh getOptExample1.sh -c 2
Output
This is demo example to use getOpt
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
USAGE
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
Available options to provide arguments:
-a : Represent first optional argument to the script
-b : Represent second optional argument to the script
-c: Represent third argument to the script
The value provided is 2
Now, let us see in the below example what happens when we provide an invalid argument.
Output5: Passing Invalid argument
Run the following command to get the output:
$ sh getOptExample1.sh -d
Output
This is demo example to use getOpt
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
USAGE
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
Available options to provide arguments:
-a : Represent first optional argument to the script
-b : Represent second optional argument to the script
-c: Represent third argument to the script
getOptExample1.sh: illegal option -- d
script usage: $0 [-a] [-b] [-c somevalue]
Let us now try providing one valid and one invalid argument, as shown in the following example.
Output6: Passing one valid and one invalid argument
Run the following command to get the output:
$ sh getOptExample1.sh -a -d
Output
This is demo example to use getOpt
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
USAGE
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
Available options to provide arguments:
-a : Represent first optional argument to the script
-b : Represent second optional argument to the script
-c: Represent third argument to the script
a represents the first argument
getOptExample1.sh: illegal option -- d
script usage: $0 [-a] [-b] [-c somevalue]
To understand a program better, there is nothing better than trying it and seeing its results. Looking at the above examples, I am sure you might have been able to understand the concept slightly. If not, then we will now understand it line by line.
Example Script Description
We have used a combination of a while loop and switch case to parse through all the options that we can provide to the program.
- In this example, -a, -b, and -c are the valid options that we can provide, and based on the match, the case statements will be executed as can be seen in the above output examples.
- Another point of observation is we need to exit the program ourselves if any error occurs; otherwise, the script will keep executing. In the above example, we have used exit 1 to exit in case of invalid inputs.
- In case no option is provided, it will leave the parsing step and will execute the remaining script.
Example:
vi getOptExample1.sh
echo "This is demo example to use getOpt"
echo "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
echo " USAGE "
echo "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
echo "Available options to provide arguments: "
echo "-a : Represent first optional argument to the script"
echo "-b : Represent second optional argument to the script"
echo "-c: Represent third argument to the script"
while getopts 'abc:' OPTION; do
case "$OPTION" in
a)
echo "a represents the first argument"
;;
b)
echo "b represent second option argument which can be passed"
;;
c)
avalue="$OPTARG"
echo "The value provided is $OPTARG"
;;
?)
echo "script usage: $(basename \$0) [-a] [-b] [-c somevalue]" >&2
exit 1
;;
esac
done
echo "Execution completed"
Output
This is demo example to use getOpt
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
USAGE
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
Available options to provide arguments:
-a : Represent first optional argument to the script
-b : Represent second optional argument to the script
-c: Represent third argument to the script
Execution completed
getopts 'abc:' denote valid options that you can pass to the program, which are a, b and c. “:” after c specifies that it expects an argument value here. If the argument is not provided, it will tell in the script that the argument is required. The value provided to the argument is stored in the OPTARG variable.
$ sh getOptExample1.sh -c
Output
This is demo example to use getOpt
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
USAGE
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
Available options to provide arguments:
-a : Represent first optional argument to the script
-b : Represent second optional argument to the script
-c: Represent third argument to the script
getOptExample1.sh: option requires an argument -- c
script usage: $0 [-a] [-b] [-c somevalue]
Understanding Variations in optString
Here, we shall help you understand the variations in optString with examples.
1. getopts "atc" optname
This denotes three one-character available options, “a”, “t”, and “c”, which don’t expect any argument value. They can be invoked in combination or standalone also.
Example:
$ sh scriptfile.sh -a
$ sh scriptfile.sh -atc
$ sh scriptfile.sh -ct
Two characters are reserved, which cannot be used as an option. These characters include “:” and “?”. “:” is used to denote if any option requires a value, and “?” is used to denote an invalid option.
2. Getopts “at:c:”
This denotes three available options where -a does not require any value, -t, -c requires a mandatory value and will result in an error if it is not passed.
Example
getOptExample2.sh
#!/bin/bash
USAGE="usage: $0 -k -r -s"
echo "Initiating parsing of arguments"
while getopts 'kr:s:' optdata; do
case "$optdata" in
k)
echo "kill the job"
;;
r)
rdata=$OPTARG
echo "resume the job starting from $rdata"
;;
s)
echo "start the job from index $OPTARG"
;;
?)
echo "Please enter valid option as per usage"
echo "$USAGE"
exit 1
;;
esac
done
echo ""
echo "Completed execution of script"
Run the following command to get the output:
$ sh getOptExample2.sh -s30 -r45 -k
Output
Initiating parsing of arguments
start the job from index 30
resume the job starting from 45
kill the job
Completed execution of script
Conclusion
In this article, we have covered what the getOpts command is and how we can use it to beautify our shell scripts and provide a meaningful message to the user of the script on how to use it by adding USAGE guidelines. We also looked into the examples where we learned to create single-character options since long-character options are not supported by getopts (It can be done but with a hack where the developer has to make sure to cover the failure scenarios).
I hope the examples and output results helped to understand it better. You can try out more complex examples and enhance your learning.
Happy scripting and happy learning!
People are also reading:
Leave a Comment on this Post