getopts allows switches to have one character (like a, b, etc.). How can I customize it for handling the above situation? Or, is there any alternative to getopts?
I guess fpmurphy alludes specifically to ksh so you may be lucky there.
Option processing "by hand" is not such a big deal, either.
while true
do
case $# in 0) break ;; esac
case $1 in
-d|--dir) shift; dir=$1; shift ;;
-u|--user) shift; user=$1; shift ;;
-a|--all) shift; all=true ;;
-|--) shift; break;;
-h|--help) cat <<______EOF >&2; exit 0 ;;
Syntax: $0 [ -d directory | --dir directory ] [ -u user | --user user ] | --help
______EOF
-*) cat <<______EOF >&2; exit 2 ;;
Invalid option $1. Try $0 --help to see available options.
______EOF
*) break ;;
esac
done
When it comes to single dash vs double dash for long options, option clustering vs no option clustering, requiring and/or permitting an equals sign between a long option and its value, etc, you're in a twisty maze of conflicting standards, all equally non-standard. Personally I'd recommend double dash for long options. Permitting equals signs between options and their values would complicate the code somewhat, as would option clustering for short options (i.e. allowing -au user as a shorthand for -a -u user).
PS. I just whipped this up on the fly, but $dmr knows I've written enough of these to have some routine. It even seems to work, based on quick informal testing.