Search code examples
bashjenkinsgroovy

Passing string with single quotes from jenkins to file


In jenkins pipeline I'm defining a condition for where clause in sql statement:

else if  (params.targetEnv == "dev"){
    condition = "where DATABASENAME like '%dev%'"}

Then I want to replace the condition placeholder in sql file:

sh """sed -i 's/@condition@/${condition}/' ${sql_query_file}"""

But in the file I get where DATABASENAME like %dev% instead where DATABASENAME like '%dev%' that means without the single quotes.

Does anybody know how can I pass there the condition with the single quotes?


Solution

  • Solution

    sh "sed -i \"s/@condition@/${condition}/\" ${sql_query_file}"
    

    enter image description here

    explanation

    1. If you will use a sentence in which there is some variable, you should use double quotes. This is valid on jenkins and unix
    def condition = "foo"    
    echo "$condition"
    println "$condition"
    
    1. sed sintax need single or double quotes
    sed -i 's/SEARCH_REGEX/REPLACEMENT/g' INPUTFILE
    sed -i "s/SEARCH_REGEX/REPLACEMENT/g" INPUTFILE
    

    Double quote should be used if some var is used in the sed argument

    1. You should escape the double quote inside of sed because in the parent string there are double quotes
    echo " foo is \"bar\" "
    
    1. Putting it all togeter
    sh "sed -i \"s/@condition@/${condition}/\" ${sql_query_file}"