I\'d like to use getopts
inside a function that I have defined in my .bash_profile.
The idea is I\'d like to pass in some flags to this function to alter its be
Here is simple example of getopts usage within shell function:
#!/usr/bin/env bash
t() {
local OPTIND
getopts "a:" OPTION
echo Input: $*, OPTION: $OPTION, OPTARG: $OPTARG
}
t "$@"
t -a foo
Output:
$ ./test.sh -a bc
Input: -a bc, OPTION: a, OPTARG: bc
Input: -a foo, OPTION: a, OPTARG: foo
As @Adrian pointed out, local OPTIND
(or OPTIND=1
) needs to be set as shell does not reset OPTIND
automatically between multiple calls to getopts (man bash
).
The base-syntax for getopts
is:
getopts OPTSTRING VARNAME [ARGS...]
and by default, not specifying arguments is equivalent to explicitly calling it with "$@" which is: getopts "a:" opts "$@"
.
In case of problems, these are the used variables for getopts
to check:
OPTIND
- the index to the next argument to be processed,OPTARG
- variable is set to any argument for an option found by getopts
,OPTERR
(not POSIX) - set to 0 or 1 to indicate if Bash should display error messages generated by the getopts
.Further more, see: Small getopts tutorial at The Bash Hackers Wiki