How do I escape a single quote inside single quotes in jenkins-pipeline bash command

倖福魔咒の 提交于 2021-02-11 12:11:53

问题


in jenkins-pipeline, I'm trying to use SED to append the following line to the end of a file.

sh "sed -i '\$ s/\$/ public_file=\\/var\\/lib\\/jenkins\\/workspace\\/test-project\\ ansible_ssh_common_args='-o StrictHostKeyChecking=no'  /' file.txt"

but I can't figure out how to escape the below line in my Jenkins file to make it work.

ansible_ssh_common_args='-o StrictHostKeyChecking=no' 

I've already tried the following, which works in katacoda playground, but not in jenkins pipeline.

'"'"'-o StrictHostKeyChecking=no'"'"'  /' file.txt

回答1:


  1. use " to wrap sed command, then you can use ' in command directly without to escape it.

  2. use @, but / as delimiter for sed s command, then you no need to escape the / appeared in file path to make the whole commend more concise and readable.

sed -i "\$ s@\$@ public_file=/var/lib/jenkins/workspace/test-project ansible_ssh_common_args='-o StrictHostKeyChecking=no'  @" file.txt



回答2:


In bash, you cannot escape single quotes within single quotes.

See the bash manual page:

Enclosing characters in single quotes preserves the literal value of each character within the quotes. A single quote may not occur between single quotes, even when preceded by a backslash.

You can use double quotes instead; then escape them as needed. You can then use single quotes within them without further escaping.



来源:https://stackoverflow.com/questions/57469069/how-do-i-escape-a-single-quote-inside-single-quotes-in-jenkins-pipeline-bash-com

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!