没有 BASH,Jenkins 管道步骤 withEnv 不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40672083/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 15:25:10  来源:igfitidea点击:

Jenkins Pipeline Step withEnv does not work without BASH

bashjenkinsjenkins-pipelinejenkins-workflow

提问by Sebastian Woinar

I've trouble setting an environment variable for a container in an Jenkins pipeline. It seems, that "withEnv" does not work nicely with machines without bash.

我在 Jenkins 管道中为容器设置环境变量时遇到问题。看来,“withEnv”在没有 bash 的机器上不能很好地工作。

Can you confirm that? I cannot find an official statement ;-)

你能确认吗?我找不到官方声明;-)

When I run the following snippet on the Jenkins slave it works. But when it is executed in a docker container without BASH "$test" isn't set.

当我在 Jenkins slave 上运行以下代码片段时,它可以工作。但是当它在没有 BASH 的 docker 容器中执行时,“$test”没有设置。

 withEnv(["test='asd'"]){
      sh 'echo $test'
 }

https://jenkins.io/doc/pipeline/steps/workflow-basic-steps/#code-withenv-code-set-environment-variables

https://jenkins.io/doc/pipeline/steps/workflow-basic-steps/#code-withenv-code-set-environment-variables

回答by Itai Ganot

If I'm not mistaken, I believe the variable is not set correctly.

如果我没记错的话,我相信变量设置不正确。

Try this:

尝试这个:

withEnv(["test=asd"]){
      sh "echo $test"
 }

Within a Jenkins pipeline:

在 Jenkins 管道中:

$var = Groovy parameter
$var (within a sh closure) = Bash parameter
${var} = also refers to Groovy parameter

In order to insert a groovy variable into a bash variable:

为了将 groovy 变量插入到 bash 变量中:

sh ("VAR=${GROOVY_VAR}")

Using a bash variable inside a sh closure:

在 sh 闭包中使用 bash 变量:

sh (" echo $BASH_VAR")

回答by Nagashayan

We have to use single quote when using withEnv in Jenkins.

在 Jenkins 中使用 withEnv 时,我们必须使用单引号。

withEnv(['test=asd']){
  sh "echo $test"

}

}

Because, the variable expansion is being done by the Bourne shell, not Jenkins. (Quoting from documentation)

因为,变量扩展是由 Bourne shell 完成的,而不是 Jenkins。(引用自文档)

Find more info here: https://jenkins.io/doc/pipeline/steps/workflow-basic-steps/

在此处查找更多信息:https: //jenkins.io/doc/pipeline/steps/workflow-basic-steps/