1

everybody, I have a problem with a stage in a Declaritive pipeline in Jenkins. I'd like Jenkins to check if the directory /root/elp contains data with the name *.php If this is the case, jenkins should execute a command. If there is nothing in the folder, Jenkins should finish the job with success.

My Code that not function :

        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" 
                    }
        }
    }
M. Antony
  • 161
  • 2
  • 3
  • 12

2 Answers2

4

Use the below:-

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

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

And you can follow check-if-a-file-exists-in-jenkins-pipeline

And you can also use below:-

def exitCode = sh script: 'find -name "*.zip" | egrep .', returnStatus: true
boolean exists = exitCode == 0
user_9090
  • 1,884
  • 11
  • 28
  • I have one more question: How can I say that no matter what file exists. But which file extension I want to have all files named *.php. my first try are : def exists = fileExists '/root/elp/*.php' but it not function – M. Antony Oct 05 '18 at 12:25
  • try with " * ", something like - def exists = fileExists '/root/elp/*.php' – user_9090 Oct 05 '18 at 12:27
  • That not work :( def exists = fileExists '/root/elp/*.php' I must say the name Otherwise, he won't do it. – M. Antony Oct 05 '18 at 12:29
  • yeah fileExists will not take wildcards, so better you install the optional Pipeline Utility Steps plugin, you can make use of the findFiles step (please refer - https://jenkins.io/doc/pipeline/steps/pipeline-utility-steps/#code-findfiles-code-find-files-in-the-workspace ) – user_9090 Oct 05 '18 at 12:34
  • Would be the new code with pipeline utility : def files = findFiles '/root/elp/*.php' ? – M. Antony Oct 05 '18 at 12:42
1

The following example is when using 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"
            }
        }
    }
}

Alternatively for scripted pipeline you may find this bash syntax to check if file exists useful.

Emil
  • 2,196
  • 2
  • 25
  • 24