Jenkins 管道文件存在,否则

Jenkins Pipeline file exists if else

各位, 我在 Jenkins 的声明性管道中遇到阶段问题。 我希望 Jenkins 检查目录 /root/elp 是否包含名称为 *.php 的数据,如果是这样,jenkins 应该执行一个命令。如果文件夹中没有任何内容,Jenkins 应该会成功完成工作。

我的代码不起作用:

        stage('Test Stage') {
        steps {
            script {
                def folder = new File( '/root/elp/test.php' )
                    if( folder.exists() ) {
                        sh "LINUX SHELL COMMAND"
                    } else {
                        println "File doesn't exist" 
                    }
        }
    }

使用以下:-

def exists = fileExists '/root/elp/test.php'

if (exists) {
    sh "LINUX SHELL COMMAND"
} else {
    println "File doesn't exist"
}

你可以关注

你也可以使用下面的方法:-

def exitCode = sh script: 'find -name "*.zip" | egrep .', returnStatus: true
boolean exists = exitCode == 0

下面的例子是在使用Jenkins declarative pipeline时:

pipeline{
    agent any
    environment{
        MY_FILE = fileExists '/tmp/myfile'
    }
    stages{
        stage('conditional if exists'){
            when { expression { MY_FILE == 'true' } }
            steps {
                echo "file exists"
            }
        }
        stage('conditional if not exists'){
            when { expression { MY_FILE == 'false' } }
            steps {
                echo "file does not exist"
            }
        }
    }
}

或者 scripted pipeline you may find this bash syntax to check if file exists 有用。