getoptions bash script Wiki
easy parsing of option parameters in bash scripts
Brought to you by:
pmheinen
Welcome to your wiki!
This is the default page, edit it as you see fit. To add a new page simply reference it within brackets, e.g.: [SamplePage].
The wiki uses Markdown syntax.
getoptions - analyse all option parameters using a list of patterns
~~~ usage: getoption [<option_list>] <p1> <p2> <p3> ...
option_list: space-separated list of option_patterns to test against the parameter(s)
p1, p3, p3: parameters to examine
reports on STDOUT:
multiline list with identified options: <option> <value> on OK
<remainder_of_a_parm> unnown option(s) (rc=255)
returncodes:
nshift nr of parms handled as options
255 unknown option(s), reported on STDOUT
parameters '-' (read from STDIN) and '--' (end of options) are handled POSIX compliant
option_pattern may require a value, like so: -x: or -x= (numeric value)
<value> is to be found in the current parm field directly after the option string,
or in the next parameter, like so: -p12, or -pABC, or -p:ABC, or -p ABC
a default value may be defined in <option_pattern>, like so: -x:ABC or -x=123
if the default value is numeric, a numeric value is expected
an embedded '*' in option_pattern defines a variable length right hand part
the option is matched if (a) full length of pattern or (b) terminated ( : = or numeric )
an embedded '?' functions likewise, and allows matching the left hand part only
matching examples:
info matches -abcinfoxyz
i*nfo matches -abcinfo, -abcinf, -abcin, -abci; but not -abcimfo
i*nfo= matches -abci:2xyz etc., returns value=2 (the value in the parameter(s))
i*nfo: matches -abci:2xyz etc., returns value=2xyz (the value in the parameter(s))
i?nfo: matches -abcinfoxyz, -abcixyz
-info matches -info, -infoxyz; but not -abcinfo
info=3 matches -abcinfoxyz, returns value=3 (the default value)
option_list may include a '?' pattern (at the end of the list):
this will catch unknown option(s), reported as <?> <remainder_of_parm1>
you are then free to apply your own error handling as required.
an option_pattern ending with '&' will collect all following option parameters
(these should all start with '-' or '--' )
an option_pattern with '~' as value separator will report the default value
option_patterns with '::' or '==' separator will not take a value from the next parm
HOWTO (example)
optlist="list vverbose f*ile:" # define our list of options
r=$(getoptions "$optlist" "$@") # analyse our parameter list
rc="$?" # keep getoptions returncode
[ "$rc" == 255 ] && errexit "unknown option(s) $r" # some incorrect option
shift "$rc" # shift out the parameters which are options
while read opt val; do # read list of <option> <value>
[ -z "$opt" ] && break # protect against empty list $r
... # process $opt and $val # you get all options seen with their values
done <<< "$r" # this feeds the response list into read loop
(c) pmheinen, 2013-2014-2015-2016, paul.heinen@gmail.com