Jenkinsfile 添加 if else 脚本?

M. *_*ony 6 bash groovy jenkins jenkins-pipeline

我想将一个简单的 if else 脚本集成到我的 Jenkinsfile 中,但我有一个小问题:

我的 Bash 脚本:

#!/bin/bash
if [ -e /root/test/*.php ];then
echo "Found file"
else
echo "Did not find file"
fi
Run Code Online (Sandbox Code Playgroud)

该脚本工作得很好,但如果我尝试集成到一个阶段,它们就不起作用:

        stage('Test') {
        steps {
            script {
                    if [ -e "/root/test/*.php" ];then
                        echo found
                    else 
                        echo not found
                }
            }
    }
Run Code Online (Sandbox Code Playgroud)

Szy*_*iak 7

管道的script步骤需要 Groovy 脚本,而不是 Bash 脚本 - https://jenkins.io/doc/book/pipeline/syntax/#script

script您可以使用sh旨在执行 shell 脚本的步骤,而不是使用步骤。像这样的东西(这只是一个例子):

stage('Test') {
    steps {
        sh(returnStdout: true, script: '''#!/bin/bash
            if [ -e /root/test/*.php ];then
            echo "Found file"
            else
            echo "Did not find file"
            fi
        '''.stripIndent())
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 非常感谢它有效:)还有一个问题 .stripIndent 和 returnStdout 到底是什么? (2认同)
  • `returnStdout` 是可选参数,如果您想捕获命令的输出,则使用它。`stripIndent()` 是一种 Groovy 方法,用于删除给定字符串中的缩进(如果没有它,从第二行开始的所有行都会有几个空格的缩进)。 (2认同)