0

can i know which part i am doing wrong. The file not in server but however, every time i execute it goes to true statement

pipeline {
   agent any

   stages{

       stage('Test') {
           steps{
                script{
                        hasWar = sh(returnStdout: true, script: 'sshpass -p ${password} ssh ${username}@123.12.32.33 \'if [ -f /home/nityo/warFile1.war ]; then echo true; else echo false; fi\'')
                        if (hasWar) {
                            echo 'Has war'                            
                        } else {
                            echo 'No war files' 
                        }
                    }
            }
       }
   }
}
salelne
  • 35
  • 5
  • I'm not very familiar with Groovy quoting rules, but in shell, you can't include a single quote in a single quoted string the way you did, see [here](https://stackoverflow.com/q/1250079/3266847). – Benjamin W. Nov 16 '20 at 15:45
  • i put is as escpae – salelne Nov 17 '20 at 02:08

1 Answers1

1

Assuming the script part echos true or false to the console in the expected conditions, there is one more thing you didn't take into account. In Groovy, every non-empty string evaluates to true when used in the context of the boolean variable. It's called Groovy Truth.

If you want to evaluate string value false to an appropriate boolean value, you have to use toBoolean() method that returns false if the string value stores false literal, and true if it stores true literal.

https://docs.groovy-lang.org/latest/html/groovy-jdk/java/lang/String.html#toBoolean()

Also, consider adding trim() to the sh() step so all whitespaces are trimmed from the output when you store it under the hasWar variable.

pipeline {
   agent any

   stages{

       stage('Test') {
           steps{
                script{
                        hasWar = sh(returnStdout: true, script: 'sshpass -p ${password} ssh ${username}@123.12.32.33 \'if [ -f /home/nityo/warFile1.war ]; then echo true; else echo false; fi\'').trim()
                        if (hasWar.toBoolean()) {
                            echo 'Has war'                            
                        } else {
                            echo 'No war files' 
                        }
                    }
            }
       }
   }
}
Szymon Stepniak
  • 40,216
  • 10
  • 104
  • 131