137

Currently i am using Jenkins pipeline script.

For running one command, I need to access a folder outside its workspace directory.

I tried sh "cd $workspace/", but it returned current workspace folder.

How I can change to root workspace directory and then cd to another folder. Please help.

wanderors
  • 2,030
  • 5
  • 21
  • 35

3 Answers3

248

You can use the dir step, example:

dir("folder") {
    sh "pwd"
}

The folder can be relative or absolute path.

tsl0922
  • 2,685
  • 1
  • 12
  • 6
  • but it will go inside that current job folder. I want to switch to jenkins workspace – wanderors Sep 17 '18 at 17:23
  • 1
    how do you go back upwards? – DanDan Jul 18 '19 at 13:57
  • 3
    @DanDan everything outside this `dir` step is 'back upwards', see also answer/example from Gonzalo Robert Diaz: https://stackoverflow.com/a/59776342/757308 – msa Mar 06 '20 at 06:50
  • Be aware that outside the dir the directory is resetted. It is not like `cd directory` in a shell. – kap May 26 '20 at 10:54
  • When I try and run sh 'git add .' inside the "folder", it throws me this error: + git add . fatal: Not a git repository (or any of the parent directories): .git – python_newbie Mar 06 '21 at 17:30
60

The dir wrapper can wrap, any other step, and it all works inside a steps block, for example:

steps {
    sh "pwd"
    dir('your-sub-directory') {
      sh "pwd"
    }
    sh "pwd"
} 
Neuron
  • 5,141
  • 5
  • 38
  • 59
34

Use WORKSPACE environment variable to change workspace directory.

If doing using Jenkinsfile, use following code :

dir("${env.WORKSPACE}/aQA"){
    sh "pwd"
}
Mazin Ibrahim
  • 7,433
  • 2
  • 33
  • 40
Raj Bangarwa
  • 484
  • 4
  • 6