If you want to get standard output and know if the command was successful, just use returnStdout and wrap it in an exception handler:
script pipeline
try { // Fails with non-zero exit if dir1 does not exist def dir1 = sh(script:'ls -la dir1', returnStdout:true).trim() } catch (Exception ex) { println("Unable to read dir1: ${ex}") }
exit:
[Pipeline] sh [Test-Pipeline] Running shell script + ls -la dir1 ls: cannot access dir1: No such file or directory [Pipeline] echo unable to read dir1: hudson.AbortException: script returned exit code 2
Unfortunately, hudson.AbortException does not have any useful method to get this exit status, so if the actual value is needed, you need to parse it in the message (pah!)
Unlike Javadoc, https://javadoc.jenkins-ci.org/hudson/AbortException.html the assembly did not fail when this exception was detected. It does not work when not caught!
Update: If you also want to get STDERR output from a shell command, several approaches are possible:
a) Redirect STDERR to STDOUT 2>&1 - but then you need to parse this from the main output, and you will not get the output if the command is not executed - because you are in the exception handler.
b) redirect STDERR to a temporary file (whose name you are preparing earlier) 2>filename (but do not forget to clear the file later) - i.e. main code becomes:
def stderrfile = 'stderr.out' try { def dir1 = sh(script:"ls -la dir1 2>${stderrfile}", returnStdout:true).trim() } catch (Exception ex) { def errmsg = readFile(stderrfile) println("Unable to read dir1: ${ex} - ${errmsg}") }
c) Go the other way, set returnStatus=true instead, do without an exception handler and always write the output to a file, that is:
def outfile = 'stdout.out' def status = sh(script:"ls -la dir1 >${outfile} 2>&1", returnStatus:true) def output = readFile(outfile).trim() if (status == 0) { // output is directory listing from stdout } else { // output is error message from stderr }
Warning: the above code applies only to Unix / Linux - Windows requires completely different shell commands.