1

这是我用来解析 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

如何解决这个问题?我的片段有什么问题?

4

2 回答 2

2

shift从处理中删除调用-r。它正在删除-wfrom ARGS

于 2012-05-21T13:56:08.457 回答
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
于 2012-05-21T13:57:27.620 回答