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
You could have done some debugging yourself, quite easily:
Hmm, your
-f
and-t
arguments are disconnected. Make them requiredTo demonstrate that the commas apparently are not strictly required in the --long definition:
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.