How to Override PATH environment variable?

I cannot override the PATH environment variable.
I have tried with environment block, and withEnv block.

With either, the PATH variable is accessible in the Jenkinsfile, as an Jenkins variable.
However when inside a shell, printing out the env, the PATH remains unchanged.

environment {
  PATH=$WORKSPACE/build-dir:$PATH
}
steps {
  withEnv(["PATH+BUILD_DIR=${WORKSPACE}/build-dir"]) {
    echo "PATH is: $PATH"
    sh 'echo "PATH is: $PATH"'
  }
}
[Pipeline] withEnv
[Pipeline] {
[Pipeline] echo
PATH is: /home/build/jenkins/workspace/pipeline-tests/pipeline-test-path/build-dir:/home/build/bin:/usr/local/bin:/usr/bin:/bin:/usr/java/jdk1.8.0_221/bin
[Pipeline] sh
+ echo 'PATH is: /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin'
PATH is: /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
[Pipeline] }
[Pipeline] // withEnv

I need to update the PATH in the running docker container, so I can use it in shell scripts within the sh step.

i believe that should be

environment {
  PATH="${env.WORKSPACE}/build-dir:${env.PATH}
}

(env. might be optional) but quotes are necessary.

i don’t see whats wrong with the second one.

What is wrong with the second one, is that the WORKSPACE is not part of the PATH.

Your soluton does not work either

  environment {
    PATH="${env.WORKSPACE}/build-dir:${env.PATH}"
  }
  stages {
    stage ('build') {
      steps {
        echo "PATH is: $PATH"
        sh 'echo "PATH is: $PATH"'
      }
    }
  }

The first print out is substituted by Groovy. Here you can see the workspace in the path.
The second print out is echo the $PATH in a shell without Groovy substitution.
It shows that the PATH I set in Jenkinsfile is not being stored in the shell environment variables.

If I add an environment variable, that does not exist in the shell environment, it works fine

  environment {
    TEST="${env.WORKSPACE}/build-dir:${env.PATH}"
  }
  stages {
    stage ('build') {
      steps {
        echo "PATH is: $PATH"
        sh 'echo "PATH is: $PATH"'
        sh 'echo "TEST is: $TEST"'
      }
    }
  }
[Pipeline] { (build)
[Pipeline] echo
PATH is: /home/build/bin:/usr/local/bin:/usr/bin:/bin:/usr/java/jdk1.8.0_221/bin
[Pipeline] sh
+ echo 'PATH is: /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin'
PATH is: /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
[Pipeline] sh
+ echo 'TEST is: /home/build/jenkins/workspace/pipeline-tests/pipeline-test-path/build-dir:/home/build/bin:/usr/local/bin:/usr/bin:/bin:/usr/java/jdk1.8.0_221/bin'
TEST is: /home/build/jenkins/workspace/pipeline-tests/pipeline-test-path/build-dir:/home/build/bin:/usr/local/bin:/usr/bin:/bin:/usr/java/jdk1.8.0_221/bin
[Pipeline] }

It cannot override an existing environment variable.

The two different PATH’s are

  1. The PATH from the docker agent
  2. The PATH from the docker container