这是我用来解析Bash中的选项的片段:
#!/bin/bash
PROGNAME=${0##*/}
PROGVERSION=0.1
wW='-4.5.5-double'
reName=
usage()
{
cat << EO
Script purpose goes here.
EO
cat <<EO | column -s\& -t
-h, --help & show this output
-r, --rename & renames confout to Your gro
-v, --version & show version information
-w, --workWith & gromax exec suffix
EO
}
SHORTOPTS="hvw:r"
LONGOPTS="help,version,workWith:rename"
ARGS=$(getopt -s bash --options $SHORTOPTS --longoptions $LONGOPTS --name $PROGNAME -- "$@")
eval set -- "$ARGS"
while true; do
case $1 in
-h|--help)
usage; exit 0;;
-v|--version)
echo "$PROGVERSION"; exit 0;;
-w|--workWith)
wW=$2; shift;;
-r|--rename)
reName="true"; shift;;
--)
shift; break;;
*)
shift; break;;
esac
shift
done
# ====================
## finally the script:
echo "rename:" $reName
echo ' wW:' $wW
此代码段仅在触发器(-r)之前解析选项(-w):
~/wrk/mlDn/vas/res/bbst: test.bash -w 'dfdff' -r
rename: true
wW: dfdff
~/wrk/mlDn/vas/res/bbst: test.bash -r -w 'dfdff'
rename: true
wW: -4.5.5-double
如何解决这个问题?我的代码片段出了什么问题?
答案 0 :(得分:2)
从shift
处理中删除对-r
的调用。它正在从-w
删除ARGS
。
答案 1 :(得分:1)
问题是你正在转移两次:一次看到-r
选项,然后再退出case
语句。这会导致您跳过-w
选项。因此,你应该只换一次。从shift
语句之外删除case
,并在其中进行所有移动。
将您的代码更改为:
while true; do
case $1 in
-h|--help)
usage; exit 0;;
-v|--version)
echo "$PROGVERSION"; exit 0;;
-w|--workWith)
wW=$2; shift 2;; # shift twice here
-r|--rename)
reName="true"; shift;;
--)
shift; break;;
*)
shift; break;;
esac
#shift # this shift is not required
done
echo "rename:" $reName
echo ' wW:' $wW