首页 > 解决方案 > 无法在 bash 中读取值多字命令行参数

问题描述

我正在编写一个具有 4 个命令行参数的 bash shell 脚本。3/4 参数是一个词,1/4 是多词。我设法获得了其中 2 个的值,但无法获得第三个和第四个的正确值。但是,如果我删除多工作参数,它会起作用。

options=$(getopt -l "help,env:,site:,cluster:,cluster-group:" -o "he:s:c:cg:" -a -- "$@")
eval set -- "$options"

while true
do
    case $1 in
        -h|--help)
            showHelp
            exit 0
            ;;
        -e|--env)
            shift
            export environment=$1
            ;;
        -s|--site)
            shift
            export site=$1
            ;;
        -c|--cluster)
            shift
            export cluster=$1
            ;;
        -cg|--cluster-group)
            shift
            export cluster_group=$1
            ;;
        --)
            shift
            break;;
    esac
    shift
done

echo $environment
echo $site
echo $cluster
echo $cluster_group

运行时sh b.sh -s S1 -e E1 -c C1 -cg CG1,输出为

E1
S1
g

我在这里做错了什么?

标签: bashcommand-linecommand-line-arguments

解决方案


As per man getopt(1):-o只识别one-character选项。

-o, --options shortopts
              The short (one-character) options to be recognized.  If
              this option is not found, the first parameter of getopt
              that does not start with a '-' (and is not an option
              argument) is used as the short options string.  Each short
              option character in shortopts may be followed by one colon
              to indicate it has a required argument, and by two colons
              to indicate it has an optional argument.  The first
              character of shortopts may be '+' or '-' to influence the
              way options are parsed and output is generated (see
              section SCANNING MODES for details).

因此,在您的情况下,您只能提及一个字母,例如:g在.-ocluster-group

options=$(getopt -l "help:,env:,site:,cluster:,cluster-group:" -o "h:e:s:c:g:" -a -- "$@")

推荐阅读