(Similar to this, but in bash.)
I have an existing bash script that uses the builtin getopts to recognize -s
(flag only - no argument). I find I use that option every time, so I would like to make it default unless -s-
or +s
is specified on the command line. However, although ksh getopts
can handle +s
, I can't find that capability in the bash getopts
manual.
My current workarounds are:
- to use
s:
so I can recognize-s-
by$OPTARG
="-"
; or - to replace
-s
with a different option, e.g.,-d
(for "don't").
However, #1 has the problem that it swallows the next argument if I accidentally specify -s
, and #2 has the problem that it uses a different switch letter than the one I already have in my muscle memory. I am hoping there might be a straightforward way to parse -s-
or +s
in bash.
- The util-linux getopt(1) also doesn't appear to have
+s
. It can handle optional arguments, so might be able to take-s-
. However, I've not usedgetopt(1)
before so would appreciate pointers on how not to shoot myself in the foot. - BashFAQ 035 says "parse it yourself." if you have a routine already written that does
+s
or-s-
, I'd love to see it.
My current arg-parsing loop is very basic:
while getopts "nthps" opt ; do
case "$opt" in
<other cases cut>
(s) saw_s="yes"
;;
esac
done
shift $((OPTIND-1))