Bash getopts:读取可选标志的$OPTARG?

我希望能够在我的脚本中接受强制和可选标志.这是我到目前为止.
#!bin/bash

while getopts ":a:b:cdef" opt; do
      case $opt in
        a ) APPLE="$OPTARG";;
        b ) BANANA="$OPTARG";;
        c ) CHERRY="$OPTARG";;
        d ) DFRUIT="$OPTARG";;
        e ) eggplant="$OPTARG";;
        f ) fig="$OPTARG";;
        \?) echo "Invalid option: -"$OPTARG"" >&2
            exit 1;;
        : ) echo "Option -"$OPTARG" requires an argument." >&2
            exit 1;;
      esac
    done
echo "Apple is "$APPLE""
echo "Banana is "$BANANA""
echo "Cherry is "$CHERRY""
echo "Dfruit is "$DFRUIT""
echo "eggplant is "$eggplant""
echo "fig is "$fig""

但是,输出如下:

bash script.sh -a apple -b banana -c cherry -d dfruit -e eggplant -f fig

输出

Apple is apple
Banana is banana
Cherry is 
Dfruit is 
eggplant is 
fig is

你可以看到,可选标志并没有使用$OPTARG牵引参数,因为它与所需的标志一样.有没有办法读取$OPTARG在可选标志,而不会摆脱整洁的“:)”错误处理?

=======================================

编辑:我按照吉尔伯特的建议,清理下来.这是我做的:

#!/bin/bash

  if [[ "$1" =~ ^((-{1,2})([Hh]$|[Hh][Ee][Ll][Pp])|)$]]; then
    print_usage; exit 1
  else
    while [[ $# -gt 0 ]]; do
      opt="$1"
      shift;
      current_arg="$1"
      if [[ "$current_arg" =~ ^-{1,2}.* ]]; then
        echo "WARNING: You may have left an argument blank. Double check your command." 
      fi
      case "$opt" in
        "-a"|"--apple"      ) APPLE="$1"; shift;;
        "-b"|"--banana"     ) BANANA="$1"; shift;;
        "-c"|"--cherry"     ) CHERRY="$1"; shift;;
        "-d"|"--dfruit"     ) DFRUIT="$1"; shift;;
        "-e"|"--eggplant"   ) eggplant="$1"; shift;;
        "-f"|"--fig"        ) fig="$1"; shift;;
        *                   ) echo "ERROR: Invalid option: \""$opt"\"" >&2
                              exit 1;;
      esac
    done
  fi

  if [[ "$APPLE" == "" || "$BANANA" == "" ]]; then
    echo "ERROR: Options -a and -b require arguments." >&2
    exit 1
  fi

非常感谢大家.到目前为止这完美无瑕.

大多数shell getopts一直在烦恼我很长时间,包括缺乏可选参数的支持.

但是,如果您愿意使用“–posix”样式参数,请访问bash argument case for args in $@

相关文章

用的openwrt路由器,家里宽带申请了动态公网ip,为了方便把2...
#!/bin/bashcommand1&command2&wait从Shell脚本并行...
1.先查出MAMP下面集成的PHP版本cd/Applications/MAMP/bin/ph...
1、先输入locale-a,查看一下现在已安装的语言2、若不存在如...
BashPerlTclsyntaxdiff1.进制数表示Languagebinaryoctalhexa...
正常安装了k8s后,使用kubect工具后接的命令不能直接tab补全...