How to execute shell command in Groovy and get the return code $?
10,179
Use Process.exitValue()
instead of (or in addition to) .text
:
def process = "echo hello world".execute()
print "Output: " + process.text
print "Exit code: " + process.exitValue()
Author by
Alex
Updated on June 05, 2022Comments
-
Alex almost 2 years
I can't get the return code (not the output or error) from executing a shell script within Groovy.
For all what I tried, it either ask me to escape or just print the $? instead of give me 1 or 0.
groovy: 75: illegal string body character after dollar sign; solution: either escape a literal dollar sign "\$5" or bracket the value expression "${5}" @ line 75, column 24.
Below are solutions I tried, all don't work.
println "../src/check_job_log.s ${it}.log".execute().text println "Check log ${it}.log completed" //assert ("echo \$?".execute().text == "1") //output = """echo $?""".execute().text println(['echo', '$?'].execute().text) // below is code for @that other guy //def process = "echo hello world".execute() def process = "../src/check_job_log.s ${it}.log".execute() print "Output: " + process.text print "Exit code: " + process.exitValue() Output: Exit code: 01
-
Alex about 5 years$ksh ../src/check_job_log.s sb_sp_get_ucd_test.sql.log $echo $? 0
-
Alex about 5 yearsYour code output is: Output: Exit code: 01. But as you can see from above the output from the command line is: 0. Why is this 01 and 0 different?
-
that other guy about 5 yearsThe output from my code should be
Output: hello world
,Exit code: 0
. Are you getting something else? -
Alex about 5 yearsI replace your hello world with my code, there is no ouput that's correct, but the exit code (01) is different from I run the same script from command line which is 0. I also tested with your code, the exit code is 01, not 0.
-
JRichardsz almost 3 yearsGood bless to groovy