0
0
JenkinsHow-ToBeginner · 4 min read

How to Use sh in Jenkins Pipeline: Simple Guide

In Jenkins Pipeline, use the sh step to run shell commands on the agent machine. Wrap your shell command as a string inside sh, like sh 'echo Hello', to execute it during the pipeline run.
📐

Syntax

The sh step runs shell commands on the Jenkins agent. It takes a string with the command to execute. You can use single or double quotes around the command.

Basic syntax:

  • sh 'command' - runs the command as a shell script.
  • sh(script: 'command', returnStdout: true) - runs the command and returns its output.
groovy
sh 'your-shell-command'

// Example with output capture
def output = sh(script: 'echo Hello', returnStdout: true).trim()
💻

Example

This example shows a simple Jenkins Pipeline that uses sh to run shell commands. It prints a message and captures the output of a command.

groovy
pipeline {
    agent any
    stages {
        stage('Run Shell') {
            steps {
                sh 'echo Running shell command'
                script {
                    def output = sh(script: 'date', returnStdout: true).trim()
                    echo "Current date is: ${output}"
                }
            }
        }
    }
}
Output
Running shell command [Pipeline] echo Current date is: Sat Jun 15 12:34:56 UTC 2024
⚠️

Common Pitfalls

Common mistakes when using sh include:

  • Not quoting the command string properly, causing syntax errors.
  • Expecting output without setting returnStdout: true.
  • Running Windows commands on Linux agents or vice versa.
  • Not trimming output, which can include unwanted newlines.

Always test commands on the target agent OS.

groovy
/* Wrong: missing quotes around command */
// sh(echo Hello)

/* Right: quotes included */
sh 'echo Hello'

/* Wrong: expecting output without returnStdout */
def output = sh('echo Hello')

/* Right: capture output */
def output = sh(script: 'echo Hello', returnStdout: true).trim()
📊

Quick Reference

UsageDescription
sh 'command'Run shell command, no output returned
sh(script: 'command', returnStdout: true)Run command and capture output
sh(script: 'command', returnStatus: true)Run command and get exit code
sh label: 'Run script', script: 'command'Run command with a label for logs

Key Takeaways

Use sh 'command' to run shell commands in Jenkins Pipeline.
Add returnStdout: true to capture command output as a string.
Always quote your shell commands properly to avoid syntax errors.
Test shell commands on the agent OS to ensure compatibility.
Trim output strings to remove extra newlines when capturing output.