bash 在 Jenkins 管道文件的 shell 命令中转义双引号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/56583357/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 17:07:59  来源:igfitidea点击:

Escape double quotes in a Jenkins pipeline file's shell command

bashjenkinsgroovy

提问by Archit Arora

Below is a snippet from my Jenkins file -

以下是我的 Jenkins 文件中的一个片段 -

stage('Configure replication agents') {
            environment {
                AUTHOR_NAME="XX.XX.XX.XX" 
                PUBLISHER_NAME="XX.XX.XX.XX"
                REPL_USER="USER"
                REPL_PASSWORD="PASSWORD"
                AUTHOR_PORT="4502"
                PUBLISHER_PORT="4503"
                AUTHOR="http://${AUTHOR_NAME}:${AUTHOR_PORT}"
                PUBLISHER="http://${PUBLISHER_NAME}:${PUBLISHER_PORT}"
                S_URI= "${PUBLISHER}/bin/receive?sling:authRequestLogin=1"
            }
            steps {
                sh 'curl -u XX:XX --data "status=browser&cmd=createPage&label=${PUBLISHER_NAME}&title=${PUBLISHER_NAME}&parentPath =/etc/replication/agents.author&template=/libs/cq/replication/templates/agent" ${AUTHOR}/bin/wcmcommand'
            }

The above command, in Jenkins console, is printed as

上面的命令,在 Jenkins 控制台中,打印为

curl -u XX:XX --data status=browser&cmd=createPage&label=XXXX&title=XXX&parentPath =/etc/replication/agents.author&template=/libs/cq/replication/templates/agent http://5XXXX:4502/bin/wcmcommand

Note how the double quotes ""are missing.

注意双引号""是如何丢失的。

I need to preserve the double quotes after --datain this command. How do I do it? I tried using forward slashes but that didnt work.

我需要--data在此命令之后保留双引号。我该怎么做?我尝试使用正斜杠,但没有用。

Cheers

干杯

回答by Dominik Gebhart

To expand on my comment, a quick test revealed its the case.

为了扩展我的评论,一个快速测试揭示了它的情况。

You need to escape twice, once the quote for the shell with a slash, and once that slash with a slash for groovy itself.

您需要转义两次,一次是用斜线表示 shell 的引号,另一次是用斜线表示 groovy 本身。

node() {
    sh 'echo "asdf"'
    sh 'echo \"asdf\"'
    sh 'echo \"asdf\"'
}

Result

结果

[Pipeline] {
[Pipeline] sh
+ echo asdf
asdf
[Pipeline] sh
+ echo asdf
asdf
[Pipeline] sh
+ echo "asdf"
"asdf"
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline

回答by teejay

After long time of struggling and googling, this is what has worked for me on similar use case:

经过长时间的挣扎和谷歌搜索,这就是在类似用例中对我有用的方法:

sh("ssh [email protected] \"su user -c \\"mkdir ${newDirName}\\"\"")