【问题标题】:Using git rev-parse with --parseopt to access named arguments in a shell script使用带有 --parseopt 的 git rev-parse 访问 shell 脚本中的命名参数
【发布时间】:2016-05-25 12:54:16
【问题描述】:

--parseopt 选项与git rev-parse 一起使用时,它会输出一个可以传递给eval 的字符串,例如

set -- --foo --bar=arg 'test' --

通过eval 运行此命令后,它会将$1 设置为“--foo”,将$2 设置为“--bar=arg”,并将$3 设置为“test”。我的问题是,除了设置允许我的脚本按名称访问选项的位置参数之外,set 命令是否还有任何魔力?还是我必须手动遍历参数并自己检查名称?

【问题讨论】:

    标签: linux git shell scripting git-bash


    【解决方案1】:

    没有什么魔法,但您可以将evaled 更改为其他内容,这样您就可以按名称访问。例如:

    $ eval `git rev-parse --foo --bar=arg | sed -r 's/--//g; /^[^=]+$/s/$/=/'
    $ echo $bar
    arg
    $ [[ ${foo+t} ]] && echo y
    y
    $ if [[ ${baz+t} ]]; then echo y; else echo n; fi
    n
    

    sed 删除前导 -- 并且对于没有 = 的行,在末尾添加一个。当 shell 评估像 foo= 这样的行时,它会将名为 foo 的变量设置为空字符串。您可以测试foo 是否设置为[[ ${foo+t} ]]t 是任意的,我选择t 作为真实的助记符)。您还可以将变量设置为 sed 中的某个标记值,然后使用简单的[[ $foo ]] 测试。

    根据您需要支持的各种参数,您可能需要调整 sed.使用 set -xv 将向您展示正在发生的一切,以便您进行更改:

    $ set -xv
    $ eval `git rev-parse --foo --bar=arg | sed -r 's/--//g; /^[^=]+$/s/$/=/'`
    eval `git rev-parse --foo --bar=arg | sed -r 's/--//g; /^[^=]+$/s/$/=/'`
    git rev-parse --foo --bar=arg | sed -r 's/--//g; /^[^=]+$/s/$/=/'
    ++ sed -r 's/--//g; /^[^=]+$/s/$/=/'
    ++ git rev-parse --foo --bar=arg
    + eval foo= bar=arg
    foo= bar=arg
    ++ foo=
    ++ bar=arg
    

    【讨论】:

    • 谢谢;我想我得熟悉sed。虽然没有真正看到--parseopt 的意义。
    • 使用--parseopt,您可以使用opt-spec 指定可接受的标志。任何未知标志都会导致错误。
    • 关于sed,这恰好是我使用的工具。还有其他选项,例如awk。尽管如此,正则表达式的使用在 Linux/Unix/OS X 上的文本处理中非常普遍。
    猜你喜欢
    • 1970-01-01
    • 2013-03-25
    • 2013-09-01
    • 2020-11-23
    • 2016-12-10
    • 2020-08-16
    • 2012-11-15
    • 2018-11-18
    • 2016-11-28
    相关资源
    最近更新 更多