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" } } } 

2 Answers 2

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 
Sign up to request clarification or add additional context in comments.

5 Comments

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
try with " * ", something like - def exists = fileExists '/root/elp/*.php'
That not work :( def exists = fileExists '/root/elp/*.php' I must say the name Otherwise, he won't do it.
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 - jenkins.io/doc/pipeline/steps/pipeline-utility-steps/… )
Would be the new code with pipeline utility : def files = findFiles '/root/elp/*.php' ?
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.