To add options, I have the following in one of my scripts:
parse_opts() {
while [ $# -gt 0 ]; do
case "$1" in
-h|--help)
help=1
shift
;;
-r|--raw)
raw=1
shift
;;
-c|--copy)
copy=1
shift
;;
-s|--sensitive)
sensitive=1
shift
;;
-i|--insensitive)
insensitive=1
shift
;;
*)
shift
;;
esac
done
}
There is only one problem, I cannot use multiple options at the same time. For example, using -r -s
works but using -rs
does not. How can I programmatically make it work without adding separate entries? The shell I am using is sh.
Edit: I figured out how to do it. It is based on this stackoverflow answer. I copied and pasted it but replaced it with what I need.
New code:
while getopts hcsi-: OPT; do
# Support long options: https://stackoverflow.com/a/28466267/519360
if [ "$OPT" = "-" ]; then
OPT="${OPTARG%%=*}"
OPTARG="${OPTARG#$OPT}"
OPTARG="${OPTARG#=}"
fi
case "$OPT" in
h|help) help; exit 0 ;; # Call the `help´ function and exit.
c|copy) copy=1 ;;
s|sensitive) case_sensitivity="sensitive" ;;
i|insensitive) case_sensitivity="insensitive" ;;
??*) printf '%s\n' "Illegal option --$OPT" >&2; exit 2 ;;
?) exit 2 ;; # Error reported via `getopts´
esac
done
shift $((OPTIND-1)) # Remove option arguments from the argument list
getopts
? – FelixJN Jul 05 '22 at 08:39getopts
from ksh93 does long options though (and not even the same was as GNUgetopt_long()
does).util-linux
getopt
can do it though. – Stéphane Chazelas Jul 05 '22 at 10:06getopts
, how can I use it? – Amarakon Jul 05 '22 at 20:37getopt
, as recommended by Stéphane. Thegetopts
command is a more powerful builtin which directly modifies shell variables, but you'd have to switch to bash or ksh93. – Henk Langeveld Jul 05 '22 at 21:08getopts
(with the s) is supported in Dash too, and it's a standard (builtin) utility. But it doesn't do long options in most shells.getopt
(without the s) isn't standard, and though you get combined short options as well as long options with the util-linux one (which indeed you linked to), you need to be careful to not get the "tradional" ones which can't deal with whitespace in the arguments (and maybe other things) – ilkkachu Jul 05 '22 at 21:58getopts
could be used with an additional-
option taking an argument. All arguments could be handled as normal withgetopts
and the-
option and its option-argument could be handled by an innercase
statement. Just thinking aloud... – Kusalananda Jul 05 '22 at 22:38-
the same as letters, it'd eat-- foo
(with the space) as the option and option-argument, but it seems to be smarter than that. – ilkkachu Jul 05 '22 at 22:49getopts
makes it vastly more capable than your own implementation. For example, your code doesn't support combining options, like-rc
, nor does your code complain given invalid options, nor does it support arguments to options. Follow that link for a better solution implementing long and short options with optional arguments and proper errors. – Adam Katz Mar 08 '23 at 19:54