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.

3 Answers 3

248

You can use the dir step, example:

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

The folder can be relative or absolute path.

5
  • but it will go inside that current job folder. I want to switch to jenkins workspace
    – wanderors
    Sep 17, 2018 at 17:23
  • 1
    how do you go back upwards?
    – DanDan
    Jul 18, 2019 at 13:57
  • 3
    @DanDan everything outside this dir step is 'back upwards', see also answer/example from Gonzalo Robert Diaz: stackoverflow.com/a/59776342/757308
    – msa
    Mar 6, 2020 at 6:50
  • Be aware that outside the dir the directory is resetted. It is not like cd directory in a shell.
    – kap
    May 26, 2020 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 Mar 6, 2021 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"
} 
0
35

Use WORKSPACE environment variable to change workspace directory.

If doing using Jenkinsfile, use following code :

dir("${env.WORKSPACE}/aQA"){
    sh "pwd"
}
2
  • 18
    dir('aQA') works the same way. No need for that complexity
    – Kirill
    Oct 22, 2020 at 13:38
  • 2
    What if you want to make sure to run the command in the root directory of the workspace? Jul 29, 2022 at 17:24

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.