【问题标题】:illegal string body character after dollar sign : either escape a literal dollar sign "\$5" or bracket the value expression美元符号后的非法字符串主体字符:转义文字美元符号“\$5”或将值表达式括起来
【发布时间】:2020-12-06 10:08:18
【问题描述】:

我正在尝试在 jenkins 管道中执行 git checkout 并尝试仅找出特定文件中添加的行。 然而,动态分支名称上的美元符号让我犯了错误,但同样的事情在管道的其他地方也有效。代码中唯一的新增内容是 git diff 行,用于仅查找特定文件中添加的新行。你能帮我实现吗?

工作代码:

script{
    withCreentials(...){
    
        sh returnStdout: true, script: """
            gwit checkout -B ${env.branch}
            git config user.name 'xxx'
            git config user.email 'xxx@xxx.com'
            git add sample.txt
            git commit -m "updated from pipeline"
            git push origin HEAD:${env.branch}
        
        """
    }

}

代码无效:

script{
    withCreentials(...){
        sh returnStdout: true, script: """
            git checkout -B ${env.branch}
            git config user.name 'xxx'
            git config user.email 'xxx@xxx.com'
            git diff HEAD^:sample.txt HEAD:sample.txt --color=always|perl -wine 'print $1 if /^\e\[32m\+\e\[m\e\[32m(.*)\e\[m$/'> output.txt
        
    }

}

错误是:

illegal string boy character
solution: either escape a literal dollar sign "\$5" or bracket the value expression "${5}" 
    git  checkout -B ${env.branch}
                                 ^

【问题讨论】:

  • 您可以先将多行命令拆分为几个单行命令,然后查看是哪一行导致了问题。
  • 如果我删除上面提到的 git diff 命令..一切运行正常..但是当我添加它时,错误指向结帐行..这就是为什么很难理解这个问题
  • 您的线路有print $1,错误为either escape a literal dollar sign "\$5" or bracket the value expression "${5}"。您是否尝试按照错误消息的提示进行修复?
  • 试过..没有运气..但很确定问题是在 git diff 命令中转义......直到现在我无法解决

标签: git jenkins groovy gitlab jenkins-pipeline


【解决方案1】:

这是一个非常常见的错误,基本上,在使用 Triple-Double-Quote 时,您需要对所有 $ 进行转义,除了那些您想要扩展为变量插值的一部分。

但是,Groovy 在第一次出现 $ 时打印错误,而不是实际出现错误的位置

在你的情况下,有问题的行是

git diff HEAD^:sample.txt HEAD:sample.txt --color=always|perl -wine 'print $1 if /^\e\[32m\+\e\[m\e\[32m(.*)\e\[m$/'> output.txt

您有$1[m$。解决方案是逃避这些。

另一方面,您需要避免脚本需要的任何反弹

官方文档http://docs.groovy-lang.org/latest/html/documentation/index.html#all-strings

【讨论】:

    猜你喜欢
    • 2019-08-22
    • 1970-01-01
    • 1970-01-01
    • 2013-05-28
    • 2015-08-21
    • 1970-01-01
    • 2018-01-16
    • 1970-01-01
    • 2021-04-25
    相关资源
    最近更新 更多