'how to go inside a specific directory and run commands inside it in a jenkins pipeline

I am trying to run a gradle command inside a jenkins pipeline and for that i should cd <location> where gradle files are. I added a cd command inside my pipeline but that is not working. I did this

 stage('build & SonarQube Scan') {
    withSonarQubeEnv('sonarhost') {
      sh 'cd  $WORKSPACE/sonarqube-scanner-gradle/gradle-basic'
      sh 'echo ${PWD}'
      sh 'gradle tasks --all'
      sh 'gradle sonarqube --debug'
    } 
  }

But the cd is not working, I tried dir step as suggested in pipeline docs, but i want to cd inside $WORKSPACE folder.

How can i fix this?



Solution 1:[1]

Jenkins resets the directory after each command. So after the first sh, it goes back to the previous location. The dir command is the correct approach, but it should be used like this:

dir('') {
}

Similar to how you have used withSonarQubeEnv

Alternatively, you can simply chain all the commands

sh 'cd $WORKSPACE/sonarqube-scanner-gradle/gradle-basic & echo ${PWD} & ...'

But this is not recommended. Since this will all be in the same command, it will run fine though.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 M B