0
0
JenkinsHow-ToBeginner · 3 min read

How to Use dir in Jenkins Pipeline: Syntax and Examples

In Jenkins Pipeline, use the dir step to change the working directory for a block of commands. Wrap the commands inside dir('folderName') { ... } to run them in that folder.
📐

Syntax

The dir step changes the current working directory for the commands inside its block.

  • dir('path') { ... }: Runs the enclosed commands inside the specified path.
  • The path can be relative or absolute.
  • Commands inside the block run as if you changed directory to path.
groovy
dir('subfolder') {
    // commands here run inside 'subfolder'
}
💻

Example

This example shows how to use dir to run shell commands inside a subfolder named app. It lists files in the root and then inside app.

groovy
pipeline {
    agent any
    stages {
        stage('List files') {
            steps {
                sh 'ls -l'
                dir('app') {
                    sh 'ls -l'
                }
            }
        }
    }
}
Output
total 8 -rw-r--r-- 1 user user 123 Apr 27 10:00 Jenkinsfile -rw-r--r-- 1 user user 456 Apr 27 10:00 README.md Inside app directory: total 4 -rw-r--r-- 1 user user 789 Apr 27 10:00 main.py
⚠️

Common Pitfalls

Common mistakes when using dir include:

  • Using dir without a block, which does nothing.
  • Specifying a non-existent directory, causing the build to fail.
  • Not understanding that dir only affects commands inside its block.
groovy
/* Wrong: dir used without block does nothing */
dir('app')
sh 'ls -l'  // runs in root, not in 'app'

/* Right: wrap commands inside dir block */
dir('app') {
    sh 'ls -l'
}
📊

Quick Reference

UsageDescription
dir('folder') { ... }Run commands inside 'folder' directory
dir('') { ... }Run commands in the root workspace directory
dir('nonexistent') { ... }Fails if directory does not exist
dir('folder')No effect without block

Key Takeaways

Use the dir step with a block to run commands in a specific directory.
Commands inside dir block run as if you changed to that directory.
Always ensure the directory exists to avoid build failures.
dir without a block does not change the directory for subsequent commands.
Use relative or absolute paths with dir depending on your workspace structure.