I know how to handle optional arguments using getopts in Bash
#!/bin/bash
while getopts ":a:p:drh" opt; do
case "$opt" in
a) echo $OPTARG;;
esac
done
But if my script expects ./script.sh arg1 [options]
, how do I tell getopts
to skip arg1?
$ ./script.sh -a 1234
1234
$ ./script.sh arg1 -a 1234
$ ./script.sh arg1
$ ./script.sh -a 1234 arg1
1234
As I see I can handle the argument if the argument is put in the last position. What "regex" do I need in the getopts
to allow my positional argument to be in front of the optional argument?
The suggestions from How to allow non-option arguments in any order to getopt? seems to be reordering the arguments.
If you know the number of positional arguments then you can do something like this:
Example: