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}"
}
}
}
}
}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
- How do you define and call a function (or step) in a Jenkins Groovy pipeline? [Advanced]
- How do you handle errors and retries in a Groovy pipeline (try/catch, retry, timeout)? [Advanced]
- How do you run stages in parallel in a Jenkins Groovy pipeline? [Advanced]
- What is the difference between Groovy and Java for scripting purposes? [Advanced]
- How do you securely handle secrets in a shell script (avoid hardcoding, use env or a vault)? [Advanced]
- What is idempotency, and how do you make a script safe to run repeatedly? [Advanced]
- How do you write a dry-run mode into an automation script, and why is it valuable? [Advanced]
- What is the difference between a cron job and a systemd timer? [Advanced]