【发布时间】:2014-03-17 15:31:43
【问题描述】:
我尝试实现具有多个选项的脚本。我从doc 开始,遇到一些错误,转到浏览器。阅读一些链接并在 SO 上找到它:Using getopts in bash shell script to get long and short command line options。
所以我读了它并重写了我的剧本。我在某个地方犯了一个错误。我哪里错了?
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
【问题讨论】:
-
运行你的脚本
sh -x ./opt2.sh ..... -
如果我在 opt2.sh 上使用 chmod +x 则不会。
-
@aloisdg Kevin 提到的
-x并不意味着执行,它设置了 xtrace shell 选项,该选项将导致 shell 脚本执行的每个语句都打印到控制台。这样你就可以看到你的脚本哪里出错了。