【问题标题】:Parsing obligatory parameter with colon using getopts使用 getopts 用冒号解析强制参数
【发布时间】:2021-09-26 16:09:20
【问题描述】:

是否有可能在 bash 中使用 getopt 解析包含冒号的强制参数?

假设我准备了如下代码:

    while getopts "qt:i:" arg; do
        case "$arg" in
             :)
                HOST=$(printf "%s\n" "$1"| cut -d : -f 1)
                PORT=$(printf "%s\n" "$1"| cut -d : -f 2)
                shift 1
                ;;
            -q)
                QUIET=1
                shift 1
                ;;
            -t)
                TIMEOUT="$2"
                if [ "$TIMEOUT" = "" ]; then break; fi
                shift 2
                ;;
            -i)
                INTERVAL="$2"
                if [ "$INTERVAL" = "" ]; then break; fi
                shift 2
                ;;
            -h)
                usage 0
                ;;
            *)
                echoerr "Unknown argument: $1"
                usage 1
                ;;
        esac
    done

完整代码可以在这里找到:https://pastebin.com/1eFsG8Qn

我如何调用脚本:

wait-for database:3306 -t 60 -i 10

问题是这个逻辑无法解析 HOST_URL:PORT。 任何提示如何解析它?

【问题讨论】:

  • 这是一个冒号,不是分号。问题是getopts 一旦找到不以- 开头的内容就会停止解析。
  • 感谢您发现命名错误:) 这是否意味着 getopts 在这种情况下不起作用?
  • 是的;如果你想允许位置参数在选项之前,你需要使用其他东西(比如 GNU getopt),或者自己解析参数。

标签: bash shell getopts


【解决方案1】:

是否有可能在 bash 中使用 getopt 解析包含冒号的强制参数?

当然 - 他们必须在选项之后。

wait-for -t 60 -i 10 database:3306

然后:

while getopts .... ;do
    case ...
    blabla) .... ;;
    esac
done
shift "$(($OPTIND-1))"
printf "Connect to %s\n" "$1"      # here

参数中的冒号无论如何都无关紧要。

任何提示如何解析它?

使用getopt - 它会重新排序参数。

【讨论】: