7

How to add an 'export' unix command in a Jenkins pipeline? I have a Jenkins 'stage' and 'steps' within it. What is the syntax for an export command. I need to set the environment variable 'PATH' using the export command.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
OnePlus
  • 125
  • 1
  • 2
  • 10

1 Answers1

17

You can update the $PATH like this:

pipeline {
  agent { label 'docker' }
  stages {
    stage ('build') {
      steps {

        // JENKINSHOME is just a name to help readability
        withEnv(['PATH+JENKINSHOME=/home/jenkins/bin']) {
          echo "PATH is: $PATH"
        }
      }
    }
  }
}

When I run this the result is:

[Pipeline] echo
PATH is: /home/jenkins/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games

What the heck is this PATH+JENKINSHOME syntax? Quoting from a blog at designhammer.com:

This:

/my/additional/path:$PATH

is expressed as:

PATH+ANYSTRING=/my/additional/path.

ANYSTRING is just a name to help readability. If it doesn't help readability, in your view, you can omit it. So this is equivalent:

PATH+=/my/additional/path

The above (withEnv) allows you to update the $PATH for a specific part of your pipeline. To update the $PATH for the entire pipeline, you can't use the PATH+ANYSTRING syntax, but this works:

pipeline {
  agent { label 'docker' }
  environment {
    PATH = "/hot/new/bin:$PATH"
  }
  stages {
    stage ('build') {
      steps {
        echo "PATH is: $PATH"
      }
    }
  }
}

Produces output:

[Pipeline] echo
PATH is: /hot/new/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games
burnettk
  • 13,557
  • 4
  • 51
  • 52
  • When running in a docker container the `$PATH` needs to be escaped, otherwise it will be expanded in Jenkins not in the container. When used in the `steps` block. – Qsiris Apr 25 '18 at 14:10
  • 2
    Setting `PATH` in the `stage` `environment` block does not work. I haven't figured out why. If I set it in the main `environment` block from `pipeline` then the whole pipeline is affected, which I don't need. I need this just for the testing stage. I've ended up with `export PATH=foo:\$PATH` in the `sh` block in `steps`. This works. – Qsiris Apr 25 '18 at 14:13
  • 1
    It wasn't working in `environment` for me because `PATH` was nil, so this had the effect of overriding the path. I ended up just using absolute paths to my executables. – Max May 29 '18 at 14:09
  • What would be the equivalent if jenkins is on Windows? – warchantua Jul 31 '21 at 14:56