Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a file exists in jenkins pipeline

I am trying to run a block if a directory exists in my jenkins workspace and the pipeline step "fileExists: Verify file exists" in workspace doesn't seem to work correctly.

I'm using Jenkins v 1.642 and Pipeline v 2.1. and trying to have a condition like

if ( fileExists 'test1' ) {   //Some block } 

What are the other alternatives I have within the pipeline?

like image 217
Balualways Avatar asked Jul 22 '16 20:07

Balualways


People also ask

How do I delete a file in Jenkins pipeline?

Navigate to /scriptApproval/ (Manage Jenkins > In-process Script Approval) and approve the script. File. delete works on master.

How do I catch exceptions in Jenkins pipeline?

try/catch is scripted syntax. So any time you are using declarative syntax to use something from scripted in general you can do so by enclosing the scripted syntax in the scripts block in a declarative pipeline. So your try/catch should go inside stage >steps >script.

What is $workspace in Jenkins?

The workspace directory is where Jenkins builds your project: it contains the source code Jenkins checks out, plus any files generated by the build itself. This workspace is reused for each successive build.


2 Answers

You need to use brackets when using the fileExists step in an if condition or assign the returned value to a variable

Using variable:

def exists = fileExists 'file'  if (exists) {     echo 'Yes' } else {     echo 'No' } 

Using brackets:

if (fileExists('file')) {     echo 'Yes' } else {     echo 'No' } 
like image 115
Gergely Toth Avatar answered Sep 18 '22 14:09

Gergely Toth


The keyword "return" must be used

stage('some stage') {     when { expression { return fileExists ('myfile') } }     steps {            echo "file exists"           }     } 
like image 35
Roman Avatar answered Sep 17 '22 14:09

Roman