问题
I try to achieve a script with multi options. I started with the doc, get some errors, went to the browser. Read some links and find this on SO : Using getopts in bash shell script to get long and short command line options.
So I read it and rewrote my script. I made a mistake somewhere. Where am I wrong ?
SH
#!/bin/sh
TEMP=`getopt -o vfts: --long verbose,format,type,style: \
-n 'opt2' -- "$@"`
if [ $? != 0 ] ; then echo "Terminating..." >&2 ; exit 1 ; fi
eval set -- "$TEMP"
VERBOSE=false
FORMAT=
TYPE=
STYLE=
while true; do
case "$1" in
-v | --verbose ) VERBOSE=true; shift ;;
-f | --format ) FORMAT="$2"; shift 2 ;;
-t | --type ) TYPE="$2"; shift 2 ;;
-s | --style ) STYLE="$2"; shift 2 ;;
-- ) shift; break ;;
-*) break ;;
* ) break ;;
esac
done
echo "verbose = $VERBOSE"
echo "format = $FORMAT"
echo "type = $TYPE"
echo "style = $STYLE"
Output
> ./opt2.sh -v -f fofo -t toto -s soso
verbose = true // ok
format = -t // should be fofo
type = // should be toto
style = soso // ok
回答1:
Your options string is wrong, it should be vf:t:s:
. The colon indicates a required argument which each of your options except for v has. Also need to adjust your long options string accordingly.
回答2:
You could have done some debugging yourself, quite easily:
$ set -- -v -f fofo -t toto -s soso
$ TEMP=$(getopt -o vfts: --long verbose,format,type,style: -- "$@")
$ echo "$TEMP"
-v -f -t -s 'soso' -- 'fofo' 'toto'
Hmm, your -f
and -t
arguments are disconnected. Make them required
$ TEMP=$(getopt -o vf:t:s: --long verbose,format:,type:,style: -- "$@")
$ echo "$TEMP"
-v -f 'fofo' -t 'toto' -s 'soso' --
To demonstrate that the commas apparently are not strictly required in the --long definition:
$ TEMP=$(getopt -o vf:t:s: --long verbose,format:type:style: -- "$@")
$ echo $?; echo "$TEMP"
0
-v -f 'fofo' -t 'toto' -s 'soso' --
来源:https://stackoverflow.com/questions/22458520/how-to-use-getopt-with-this-several-values