Bash 如何将getopt与这几个值一起使用?

Bash 如何将getopt与这几个值一起使用?,bash,sh,getopt,Bash,Sh,Getopt,我尝试实现一个具有多个选项的脚本。我从开始,得到一些错误,转到浏览器。请阅读一些链接并在SO上找到此链接: 所以我读了它,重写了我的剧本。我在某处犯了个错误。我错在哪里 SH #!/bin/sh TEMP=`getopt -o vfts: --long verbose,format,type,style: \ -n 'opt2' -- "$@"` if [ $? != 0 ] ; then echo "Terminating..." >&2 ; exi

我尝试实现一个具有多个选项的脚本。我从开始,得到一些错误,转到浏览器。请阅读一些链接并在SO上找到此链接:

所以我读了它,重写了我的剧本。我在某处犯了个错误。我错在哪里

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"
输出

> ./opt2.sh -v -f fofo -t toto -s soso

verbose = true // ok
format = -t // should be fofo
type =  // should be toto
style = soso // ok

您的选项字符串错误,应该是
vf:t:s:
。冒号表示除v之外的每个选项都具有的必需参数。还需要相应地调整长选项字符串。

您的选项字符串错误,应该是
vf:t:s:
。冒号表示除v之外的每个选项都具有的必需参数。还需要相应地调整长选项字符串。

您可以自己进行一些调试,非常容易:

$ 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'
嗯,您的
-f
-t
参数已断开连接。要求他们

$ TEMP=$(getopt -o vf:t:s: --long verbose,format:,type:,style: -- "$@")
$ echo "$TEMP"
 -v -f 'fofo' -t 'toto' -s 'soso' --

为了证明逗号在--long定义中显然不是严格要求的:

$ TEMP=$(getopt -o vf:t:s: --long verbose,format:type:style: -- "$@")
$ echo $?; echo "$TEMP"
0
 -v -f 'fofo' -t 'toto' -s 'soso' --

您可以自己进行一些调试,非常容易:

$ 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'
嗯,您的
-f
-t
参数已断开连接。要求他们

$ TEMP=$(getopt -o vf:t:s: --long verbose,format:,type:,style: -- "$@")
$ echo "$TEMP"
 -v -f 'fofo' -t 'toto' -s 'soso' --

为了证明逗号在--long定义中显然不是严格要求的:

$ TEMP=$(getopt -o vf:t:s: --long verbose,format:type:style: -- "$@")
$ echo $?; echo "$TEMP"
0
 -v -f 'fofo' -t 'toto' -s 'soso' --


运行脚本
sh-x./opt2.sh….
如果我在opt2.sh上使用chmod+x,则不运行脚本。@aloisdg Kevin提到的
-x
并不意味着执行,它设置了xtrace shell选项,该选项将使shell脚本执行的每个语句打印到控制台。如果我在opt2.sh上使用chmod+x,那么运行脚本
sh-x./opt2.sh….
就不会了。@aloisdg Kevin提到的
-x
并不意味着执行,它设置了xtrace shell选项,该选项将使shell脚本执行的每个语句打印到控制台。这样,您就可以看到您的脚本哪里出了问题。
verbose,format:type:style:
我想是吧?我现在就试试。我想你少了几个逗号,我少了几个逗号?它完全是这样工作的。我应该添加缺少的逗号吗?@aloisdg,意思是
verbose,format:,type:,style:
,哪一个更可读/更易于维护,即使冒号后面似乎不需要逗号。@aloisdg是否使用不带逗号的脚本测试了长选项?
verbose,format:type:style:
?我现在就试试。我想你少了几个逗号,我少了几个逗号?它完全是这样工作的。我应该添加缺少的逗号吗?@ALOISG,意思是
verbose,format:,type:,style:
,哪一个更可读/更易于维护,即使看起来您不需要在冒号后加逗号。@ALOISG是否使用不带逗号的脚本测试了长选项?没有考虑,但是是的!我没想过,但是是的!