5

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.

Siddarth
  • 351
  • 2
  • 6
  • 20
  • 2
    Have you looked at https://gist.github.com/Faheetah/e11bd0315c34ed32e681616e41279ef4 ? That might help understand some of the quirks of the escaping. – mkobit Sep 06 '18 at 13:36

3 Answers3

3

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"
Siddarth
  • 351
  • 2
  • 6
  • 20
0

if othertext is a groovy variable then this should work:

def othertext = 'newtext'
sh (script: """sed -i 's/sometext/${othertext}/' filename""", returnStdout:false)
daggett
  • 26,404
  • 3
  • 40
  • 56
  • othertext is not groovy variable. It is parameter to jenkins pipeline job. othertext is dynamic. – Siddarth Sep 06 '18 at 10:58
  • Beware of [injection by interpolation](https://www.jenkins.io/doc/book/pipeline/jenkinsfile/#injection-via-interpolation) when using variables like this. The safer alternative is to use an environment variable (and single quotes around the groovy string) – Bruno Mar 13 '23 at 09:39
0
node{
   sh 'sed -i 's/sometext/'"${othertext}"'/' filename'
}
Liam
  • 27,717
  • 28
  • 128
  • 190
Rajesh Gurram
  • 46
  • 1
  • 5