How do I make Jenkins 2.0 execute a sh command in the same directory as the checkout?

Salim Fadhley picture Salim Fadhley · Jul 1, 2016 · Viewed 87k times · Source

Here's my Jenkins 2.x pipeline:

node ('master'){
    stage 'Checkout'
    checkout scm
    stage "Build Pex"
    sh('build.sh')
}

When I run this pipeline the checkout puts the code into to the workspace as expected, however instead of expecting to find the script in workspace/ (it's really there!), it looks in an unrelated directory: workspace@tmp/durable-d812f509.

Entering stage Build Pex
Proceeding
[Pipeline] sh
[workspace] Running shell script
+ build.sh
/home/conmonsysdev/deployments/jenkins_ci_2016_interns/jenkins_home/jobs/pex/branches/master/workspace@tmp/durable-d812f509/script.sh: line 2: build.sh: command not found

How do I modify this Jenkinsfile so that build.sh is executed in the exact same directory as where I checked out the project source code?

Answer

Jayan picture Jayan · Jul 3, 2016

You can enclose your actions in dir block.

checkout scm
stage "Build Pex"
dir ('<your new directory>') { 
    sh('./build.sh')
}
... or ..
checkout scm
stage "Build Pex"
sh(""" <path to your new directory>/build.sh""")

...

<your new directory> is place holder your actual directory. By default it is a relative path to workspace. You can define absolute path, if you are sure this is present on the agent.