【问题标题】:Shell - how to access arguments passed as flagsShell - 如何访问作为标志传递的参数
【发布时间】:2022-02-17 05:36:22
【问题描述】:

我想要一个可以利用这种风格的一些可选标志的 shell 脚本:

script.sh --foo "foo message" --bar "bar message"

script.sh --foo "foo message"

script.sh --bar "bar message"

script.sh --bar "bar message" --foo "foo message"

访问这些值的最简单方法是什么(例如:“foo message”和“bar message”通过它们的标志名(例如:foo 和 bar)?

【问题讨论】:

    标签: bash shell command-line command-line-arguments


    【解决方案1】:

    使用 bash,您可以执行以下操作:

    #!/bin/bash
    args=()
    
    while test $# -gt 0; do
            case $1 in
            --foo) foo_msg=$2; shift;;
            --bar) bar_msg=$2; shift;;
            *) args+=($1);;
            esac
            shift
    done
    set -- "${args[@]}"
    
    echo "remainging args: $@"
    echo "foo_msg=$foo_msg"
    echo "bar_msg=$bar_msg"
    

    如果您使用的是不带数组的 shell,则保留其他参数会更加困难,但您通常可以在类似的循环中使用它们。

    【讨论】:

      猜你喜欢
      • 2021-07-22
      • 1970-01-01
      • 2019-03-03
      • 1970-01-01
      • 2021-10-30
      • 1970-01-01
      • 1970-01-01
      • 2020-07-04
      • 1970-01-01
      相关资源
      最近更新 更多