Interview Scripting (Bash, Groovy)

How do you run shell commands from a Groovy pipeline (sh step) and capture output? [Advanced]

Answer

In Jenkins Pipeline, I run shell commands with the sh step. To capture stdout, use returnStdout: true and trim the result. To capture the exit status without failing the build, use returnStatus: true.

Technical explanation

By default, sh fails the stage if the command exits nonzero.

returnStdout captures standard output, but stderr still appears in logs unless redirected.

Always quote shell variables carefully inside Groovy strings because Groovy interpolation and shell expansion are different layers.

Hands-on example

pipeline {

agent any

stages {

stage('Git Info') {

steps {

script {

def sha = sh(script: 'git rev-parse --short HEAD', returnStdout: true).trim()

def rc = sh(script: 'test -f Dockerfile', returnStatus: true)

echo "sha=${sha} dockerfile_rc=${rc}"

}

}

}

}

}

Preparing for an interview?

Check how well your resume matches the role with our free resume checker— match score, ATS check, and the skills you're missing.

More Scripting (Bash, Groovy) interview questions

← All Scripting (Bash, Groovy) questions