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
- What is the purpose of the shebang line, and what does #!/bin/bash do? [Basic]
- What is the difference between sh and bash? [Basic]
- How do you make a script executable and run it? [Basic]
- What is the difference between running a script with ./script.sh, bash script.sh, and source script.sh? [Basic]
- What does sourcing a script do differently from executing it? [Basic]
- How do you declare a variable in Bash, and why are spaces around = not allowed? [Basic]
- What is the difference between $var and ${var}? [Basic]
- What is the difference between single quotes and double quotes in Bash? [Basic]