【问题标题】:Unexpected operator - shell script in a Bamboo plan [duplicate]意外的运算符 - Bamboo 计划中的 shell 脚本 [重复]
【发布时间】:2021-01-24 10:17:37
【问题描述】:

我尝试在我的 Bamboo 计划中运行 shell 命令。 这是我尝试运行的代码:

[ "$(git rev-parse --abbrev-ref HEAD)" == *test* ] || [ "$(git rev-parse --abbrev-ref HEAD)" == *develop* ] && echo "yes"

这应该检查分支名称是testdevelop。如果是,那么它应该打印消息yes

我在分支 develop 上运行它,然后我得到了错误。

错误信息: [: develop: unexpected operator


更新:

这是基于 POSIX 的帖子: String comparison in bash. [[: not found 我用一个 = 替换了 ==

所以我的命令看起来:

[ "$(git rev-parse --abbrev-ref HEAD)" = *test* ] || [ "$(git rev-parse --abbrev-ref HEAD)" = *develop* ] && echo "yes"

我收到的错误信息: [: pytest.ini: unexpected operator

不知道 pytest.ini 在这里做什么。 我的应用程序使用 pytest,但在这一步中我没有运行它。

【问题讨论】:

    标签: shell bamboo


    【解决方案1】:

    单括号的问题是通配符是通过文件名扩展(通配符)扩展的。考虑一下:

    $ touch test{1,2,3,4}
    $ set -x
    $ [ "$(git rev-parse --abbrev-ref HEAD)" == *"test"* ] || [ "$(git rev-parse --abbrev-ref HEAD)" == *"develop"* ] && echo "yes"
    $ [ "$(git rev-parse --abbrev-ref HEAD)" == *"test"* ]
    ++ git rev-parse --abbrev-ref HEAD
    + '[' develop == test1 test2 test3 test4 ']'
    -bash: [: too many arguments
    

    如果你的 shell 中有双括号,那么你可以用双括号替换单括号:

    [[ "$(git rev-parse --abbrev-ref HEAD)" == *"test"* ]] \
        || [[ "$(git rev-parse --abbrev-ref HEAD)" == *"develop"* ]] && echo "yes"
    

    您也可以使用case,如下所示:

    case "$(git rev-parse --abbrev-ref HEAD)" in
        *test*|*develop*)
            echo 'yes'
            ;;
    esac
    

    注意,单开括号 ([) 只是 test 内置函数的同义词,唯一的例外是单开括号要求最后一个参数是 ]

    【讨论】:

    • 我试了一下,也报错:` [[: not found `
    • @CezarySzulc,那么您的 shell 中可能无法使用双括号。考虑使用case(我已经更新了答案)
    • 有点令人惊讶的是,case 的参数不需要引号。
    • 我使用了case,它工作正常。谢谢
    猜你喜欢
    • 1970-01-01
    • 2012-03-03
    • 2012-09-09
    • 1970-01-01
    • 1970-01-01
    • 2012-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多