How to use getopt with this several values?

吃可爱长大的小学妹 提交于 2019-12-11 18:53:56

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!