Search code examples
groovyjenkins-pipelinejenkins-groovygroovyshell

How to compare an expression to a string in groovy IF statement


I have the following IF condition in my groovy script:

if (git log -1 --pretty=format:'%an' == 'xyz')

Here all i am trying to achieve is that i need to have the value of

git log -1 --pretty=format:'%an'

equate to some string lets say here xyz I can easily do that in shell as below

if [ `git log -1 --pretty=format:'%an'` == "xyz" ]

But unable to get that to work in my groovy IF


Solution

  • If you use it in Jenkinsfile

    def log = sh(returnStdout: true, script: "git log -1 --pretty=format:'%an'").trim()
    if (log == 'xyz') {
      ...
    }
    

    If you use it in pure Groovy (below solution also work in Jenkinfile)

    def log = "git log -1 --pretty=format:'%an'".execute().text
    if (log == 'xyz') {
      ...
    }