Firstly, if you're using bash, run help getopts
. That provides a good summary of what getopts
is and what it does. Otherwise search for getopts
in the man page for your shell.
With that said, it's important to note that getopts
does not search for a particular option, it gets the next command line argument (which is always going to be in "$1"
). Its up to your script to do something with that option (and its arg if it has one), and remove it/them from the command line.
The optstring
isn't a search string, it's a validation string - it tells getopts
what options are valid and whether they're supposed to take an argument or not, so that it can either print an error message or allow your script to know that an option processing error has occurred so it can take appropriate action.
If you want to look up particular options at arbitrary times/locations in your script, then you have to do what every other program does and parse the options shortly after the script is executed, and store the results in variables.
i.e. you have to do what you say you don't want to do - there's no other way if you want to use getopts
.
There is nothing stopping you from writing your own program or function that searches the command-line for one specific option (and its value, if any), but the reason nobody does it like this is that there's no point - it's easier and more efficient to just parse all the options at once in a loop than to parse/search them as an ad-hoc query (because that search program/function will have to loop over the options and args every time its called, using either getopts
or iterating over a copy of the script's "$@"
if its a shell function, or using the libc getopt()
function if it's a standalone program).
A common way of doing this is to set the variables to their default values (if any), then process each option, changing the variables from the defaults as options are seen.
A very simple example, x and y take arguments, b is a boolean:
x=10
y=20
b=0
while getopts "x:y:b" opt; do
case "$opt" in
x) x="$2" ; shift ;;
y) y="$2" ; shift ;;
b) b=1 ;;
esac
shift
done
echo "x=$x"
echo "y=$y"
echo "b=$b"
-x 1 -x2
? Return1
and2
as an array or only2
? What if you have a-x
and-y
one undoing the other, then the order or processing is important. – Stéphane Chazelas Jun 18 '22 at 14:41