The getopt
command (part of the util-linux
package and different from getopts
) will do what you want. The bash faq has some opinions about using that, but honestly these days most systems will have the modern version of getopt
.
Consider the following example:
#!/bin/sh
options=$(getopt -o o: --long option: -- "$@")
eval set -- "$options"
while :; do
case "$1" in
-o|--option)
shift
OPTION=$1
;;
--)
shift
break
;;
esac
shift
done
echo "got option: $OPTION"
echo "remaining args are: $@"
We can call this like this:
$ ./options.sh -o foo arg1 arg2
got option: foo
remaining args are: arg1 arg2
Or like this:
$ ./options.sh arg1 arg2 -o foo
got option: foo
remaining args are: arg1 arg2
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…