In older ksh or bash, the builtin command
getopts can usually only handle short option.
But newer Korn shell may be able to handle long options as show in an other article.
If you don't have the chance to get a recent shell, or if you want to write more portable script, this article will show how to handle GNU-style long options (
-- double hyphen) using getopts with few extra lines of scripting.
(foobar_any_getopts.sh zip file attachement in this article)
The script in this article has been tested ...
... on Oracle Linux 7
... with #!/bin/ksh and #!/bin/bash shebang
| ||specifies all the option characters that the script will recognize |
if a character is followed by
if optstring start with
| ||variable which stores the current option character|
| ||[optional] specifies arguments to parse (default value is $@)|
| ||store the index of the next argument to be processed |
Initially set to 1, and needs to be reset to 1 in order to parse anything else again
| ||stores the value of the option argument found by |
How it works
getopts is usually used in a while-loop and exit when it reaches the end of options.
getopts recognizes the end of the options by any of the following conditions:
- an argument that doesn't start with
- the special argument
--, marking the end of options
- an error (for example, an unrecognized option letter)
Script example source code
foobar_any_getopts.sh is a script example to show how to use getopts with long options.
This script is also available for downloading at the end of the article.
Check how this script works
See how it manages options errors :
Now see it working without errors :
Better you test by yourself to see if it works for you.
Please leave comments and suggestions,
Enjoyed this article? Please like it or share it.