Issue
I am trying to compare two integers in jenkins script using groovy. I am getting different response each time. My doubt is how to convert the string to integer then compare it and then produce the desired output. my script looks like this:
pipeline {
agent any
stages {
stage('checkout') {
steps {
script{
dec1='5.11.03'
dec2='5.9.06'
a=dec1.split("\\.")[1]
b=dec2.split("\\.")[1]
c='10'
one="$a" as Integer
two="$b" as Integer
three="$c" as Integer
println("$one")
println("$two")
println("$one".compareTo(10))
println("$two".compareTo(10))
list1 = ("$one" >= "$three") ? 'total 7 repos' : 'total 4 repos'
list2 = ("$two" >= "$three") ? 'total 7 repos': 'total 4 repos'
println("the result for $dec1 is $list1")
println("the result for $dec2 is $list2")
}
}
}
}
}
Here I am trying to compare the second part of a decimal digit and check if it is greater than 10. If it is greater than 10 it must print 'total 7 repos' or print 'total 4 repos'. I did also try using compareTo() which is producing different result. can anyone please help me with this. Thanks in advance. The output i am getting is:
11
[Pipeline] echo
9
[Pipeline] echo
1
[Pipeline] echo
8
[Pipeline] echo
the result for 5.11.03 is total 7 repos
[Pipeline] echo
the result for 5.9.06 is total 7 repos
Solution
The problem here is that you are using quotes and $ symbols around your variables, but that is incorrect syntax. Groovy follows a Java-like syntax, and you can check the doc here on Groovy variables: https://groovy-lang.org/semantics.html#_variable_assignment
Basically, your "" and $ are the problem.
Switch your lines 11-14 with:
println(one.compareTo(10))
println(two.compareTo(10))
list1 = (one >= three) ? 'total 7 repos' : 'total 4 repos'
list2 = (two >= three) ? 'total 7 repos': 'total 4 repos'
Should solve the problem.
Answered By - M B
Answer Checked By - Robin (JavaFixing Admin)