groovy + shell : Escaping characters

天大地大妈咪最大 提交于 2019-12-11 07:58:32

问题


I am using Jenkins Pipeline using Groovy sandbox. And i am trying to run a shell script in a groovy sh function.

The original shell script is

sed -i 's/sometext/'"${othertext}"'/' filename

I am trying to replace a particular text with other text (taken dynamically). The script works fine when executed directly. But I want to use it in jenkins groovy sh function.

sh(script: '<above shell script>',  returnStdout:false)

But there is a problem of escaping characters. I tried this way of escaping character

sh (script: '''sed -i 's/sometext/othertext/' filename''', returnStdout:false)

It works fine but othertext is not taken dynamically. Can someone please help me in escaping characters with the original script? Or please suggest any other way of doing this.


回答1:


With the inputs from daggett and mkobit and i did few experiments, the following script worked well

def l_othertext = sh(script: 'echo ${othertext}', returnStdout: true).trim()
print('l_othertext='+l_othertext)
sh "sed -i 's/sometext/'${l_othertext}'/' filename"



回答2:


if othertext is a groovy variable then this should work:

def othertext = 'newtext'
sh (script: """sed -i 's/sometext/${othertext}/' filename""", returnStdout:false)



回答3:


node{
   sh 'sed -i 's/sometext/'"${othertext}"'/' filename'
}


来源:https://stackoverflow.com/questions/52201797/groovy-shell-escaping-characters

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