0
0
JenkinsHow-ToBeginner · 3 min read

How to Use Steps in Jenkins Pipeline: Syntax and Examples

In Jenkins Pipeline, steps define the individual tasks executed inside a stage. You use the steps block to list commands like sh, echo, or checkout that Jenkins runs sequentially during the build.
📐

Syntax

The steps block is placed inside a stage in a Jenkins Declarative Pipeline. It contains one or more commands that Jenkins executes in order.

Each step is a command like sh to run shell scripts, echo to print messages, or checkout to get source code.

Example structure:

  • pipeline: The main block defining the pipeline.
  • stage: A phase in the pipeline.
  • steps: Commands to run in that stage.
groovy
pipeline {
  agent any
  stages {
    stage('Example') {
      steps {
        echo 'Hello, Jenkins!'
        sh 'echo Running shell command'
      }
    }
  }
}
💻

Example

This example shows a simple Jenkins Declarative Pipeline with two stages. Each stage uses steps to run commands: printing messages and running shell commands.

groovy
pipeline {
  agent any
  stages {
    stage('Build') {
      steps {
        echo 'Starting build...'
        sh 'echo Building project'
      }
    }
    stage('Test') {
      steps {
        echo 'Running tests...'
        sh 'echo Tests passed!'
      }
    }
  }
}
Output
[Pipeline] echo Starting build... [Pipeline] sh + echo Building project Building project [Pipeline] echo Running tests... [Pipeline] sh + echo Tests passed! Tests passed!
⚠️

Common Pitfalls

Common mistakes when using steps include:

  • Placing steps outside a stage block, which causes syntax errors.
  • Using unsupported commands inside steps in Declarative Pipeline.
  • Forgetting to use sh or bat for shell commands, leading to errors.

Always ensure steps are inside stage and use supported step commands.

groovy
pipeline {
  agent any
  stages {
    stage('Wrong') {
      // Missing steps block - this is wrong
      echo 'This will cause an error'
    }
  }
}

// Correct way:
pipeline {
  agent any
  stages {
    stage('Right') {
      steps {
        echo 'This works fine'
      }
    }
  }
}
📊

Quick Reference

ElementDescriptionExample
pipelineDefines the whole pipelinepipeline { ... }
agentSpecifies where to run the pipelineagent any
stageDefines a phase in the pipelinestage('Build') { ... }
stepsContains commands to execute in a stagesteps { echo 'Hi' }
shRuns shell commandssh 'echo Hello'
echoPrints messages to consoleecho 'Message'

Key Takeaways

Use the steps block inside a stage to define commands Jenkins runs.
Each step is a command like echo or sh executed in order.
Always place steps inside a stage to avoid syntax errors.
Use sh or bat to run shell commands within steps.
Declarative Pipeline requires this structured syntax for clarity.