0

I have below code

def result = readFile('res.txt')
echo "${result}"

if ("${result}" > 5 )

{ 
        echo "Yes"
    } else {
        echo "No"
    } 
}

It is printing NO but the answer in ${result} -> 11 which means it should print Yes. Can u pls help.

Strohhut
  • 490
  • 1
  • 6
  • 22
user1628
  • 15
  • 5
  • 1
    Did you try "${result}".toInteger() > 5? My guess is you compare a String with an Integer. – Michael Kemmerzell Mar 02 '20 at 08:17
  • `readFile()` always returns a string, but you actually want a number, so you have to convert string to number. [`Integer.parseInt()` is your friend](https://www.tutorialspoint.com/groovy/groovy_parseint.htm). – zett42 Mar 02 '20 at 09:24
  • Yeah ${result}".toInteger() > 5 works for me. Thank you so much. I need to add try catch also here so that the IF statement will fail then it will stop the build and does not go to next stage. – user1628 Mar 02 '20 at 09:29
  • Does this answer your question? [How to convert String to int in Groovy the right way](https://stackoverflow.com/questions/36007867/how-to-convert-string-to-int-in-groovy-the-right-way) – zett42 Mar 02 '20 at 10:35

1 Answers1

0

As noted in comments - you should cast the result to integer. Both result.toInteger() and Integer.parseInt(result) will work, although the first one is more straightforward and doesn't complain about extra white space (e.g. trailing endline character).

Besides, you don't need to mess with strange constructs like "${result}" because result is a normal variable, so your code may look like this:

def result = readFile('res.txt')
echo "${result}"

if (result.toInteger() > 5 ) { 
    echo "Yes"
} else {
    echo "No"
}
Tupteq
  • 2,986
  • 1
  • 21
  • 30