Sam YC
Sam YC

Reputation: 11617

Jenkins pipeline "cd" command not working, "cd" vs "dir"?

I encounter an issue where cd is not working in a Window Node:

node("Window-node") {                       

    stage('unstash'){
        echo 'unstash..'

        deleteDir()                             

        unstash name: uat_stash
        unstash name: prd_stash

        bat "cd ${path}"
        bat "mkdir ${params.tag_name}"          

    }
}

The problem happen in bat "cd ${path}", it doesn't really go to the specific path, so the mkdir fails.

The path is somewhere outside of jenkins workspace, while I am using below, it works fine:

dir("${path}") {
    bat "mkdir ${params.tag_name}"
}

I am not too sure why, but I don't prefer to use dir because it will create a temp folder xxx@tmp, but never clean up after Jenkins job finished.

Anyone know why the cd fails? Or, am I able to use dir without creating a Jenkins temp folder?

Upvotes: 4

Views: 13033

Answers (2)

yong
yong

Reputation: 13712

1) Add option /d, in case cross driver, For example ${path} is in D:\, but you current in C:\

2) Wrap ${path} inside ", in case there is space in ${path}

bat """ cd /d "${path}" """

Upvotes: 2

Szymon Stepniak
Szymon Stepniak

Reputation: 42184

The first command bat "cd ${path}" does what you expect. However, the second bat step does not run in the context of the previous step, so it starts from the worker node root workspace directory.

You can solve it by replacing two bat steps with a single multiline script, e.g.

node("Window-node") {

    stage('unstash'){
        echo 'unstash..'

        deleteDir()

        unstash name: uat_stash
        unstash name: prd_stash

        bat """
            cd ${path}
            mkdir ${params.tag_name} 
        """.stripIndent().trim()
    }
}

Upvotes: 12

Related Questions