0
0
Jenkinsdevops~5 mins

Shell steps (sh, bat) in Jenkins - Commands & Configuration

Choose your learning style9 modes available
Introduction
Jenkins can run shell commands directly in its pipelines. This lets you automate tasks like building, testing, or deploying software by running simple scripts inside your pipeline.
When you want to run Linux shell commands in a Jenkins pipeline on a Linux agent.
When you need to execute Windows batch commands in a Jenkins pipeline on a Windows agent.
When you want to automate running scripts without creating separate script files.
When you want to quickly test commands inside your Jenkins pipeline.
When you need to run commands that prepare your build environment or clean up after builds.
Commands
This Jenkins pipeline runs a shell command on any available agent. The 'sh' step runs the Linux shell command to print a message.
Terminal
pipeline {
    agent any
    stages {
        stage('Run Shell') {
            steps {
                sh 'echo Hello from Linux shell'
            }
        }
    }
}
Expected OutputExpected
[Pipeline] { [Pipeline] stage [Pipeline] { (Run Shell) [Pipeline] sh + echo Hello from Linux shell Hello from Linux shell [Pipeline] } [Pipeline] // stage [Pipeline] } [Pipeline] // pipeline
This Jenkins pipeline runs a Windows batch command on any available agent. The 'bat' step runs the Windows batch command to print a message.
Terminal
pipeline {
    agent any
    stages {
        stage('Run Batch') {
            steps {
                bat 'echo Hello from Windows batch'
            }
        }
    }
}
Expected OutputExpected
[Pipeline] { [Pipeline] stage [Pipeline] { (Run Batch) [Pipeline] bat + echo Hello from Windows batch Hello from Windows batch [Pipeline] } [Pipeline] // stage [Pipeline] } [Pipeline] // pipeline
Key Concept

If you remember nothing else, remember: use 'sh' to run Linux shell commands and 'bat' to run Windows batch commands inside Jenkins pipelines.

Common Mistakes
Using 'sh' step on a Windows agent or 'bat' step on a Linux agent.
The command will fail because the shell environment does not exist on that agent type.
Use 'sh' only on Linux agents and 'bat' only on Windows agents.
Not quoting the command string inside 'sh' or 'bat' steps.
Jenkins may misinterpret the command or fail to run it properly.
Always put the command inside single quotes to ensure it runs as intended.
Summary
Use 'sh' step to run Linux shell commands in Jenkins pipelines.
Use 'bat' step to run Windows batch commands in Jenkins pipelines.
Always match the step to the agent OS to avoid errors.