File.exists() in a Jenkins groovy file do not work

groovy file exists not working
jenkins readfile example
check if file exists in jenkins
jenkins file exists directory
jenkins dir example
jenkins pipeline read file if exists
jenkins waituntil example
jenkins pipeline fileexists wildcard

I want to create a groovy function in my Jenkins job that looks into a folder and deletes all files who are older than X days.

So I start looking in the internet and found different kind of solutions.

At first I create a .groovy file with Visual Studio Code on my local PC to understand how it works. That is the reason why my code looks not similar to the codes in the internet because I changed it so that I understand how the code works.

def deleteFilesOlderThanDays(int daysBack, String path) {
  def DAY_IN_MILLIS = 24 * 60 * 60 * 1000
  File directory = new File(path)

    File[] listFiles = directory.listFiles()

    for(File listFile : listFiles) {
      def days_from_now = ( (System.currentTimeMillis() - listFile.lastModified()) /(DAY_IN_MILLIS))
      if(days_from_now > daysBack) {
        println('file is older')
          println('File is not older')
      }//End: for(File listFile : listFiles) {
    }//End: if(directory.exists()){

(I know, the code do not delete something. It is only for my understanding)

The second step was to include this new created function into my Jenkins groovy file. But since then I'm desperate.

I have the problem that I do not get a positive result at the beginning from the code if the folder really exist.

The line:


makes me a lot of problems and it is not clear for me why.

I have tried so many kind of versions but I haven’t found a solution for me. I have also used the "Pipeline Syntax" example [Sample Step fileExists] but it doesn’t help for me.

I have included:


At the beginning of my file.

I have a basic file which I include in the Jenkins job. This file includes my library files. One of this library files is the "file.groovy". In the basic Jenkins file I execute the function "file.deleteFilesOlderThanDays()" (for testing I do not use any parameters).

The code from my function for testing is:

def deleteFilesOlderThanDays() {

  dir = '.\\ABC'
  echo "1. ----------------------------------------"
  File directory1 = new File('.\\ABC\\')
  exist = directory1.exists()
  echo 'Directory1 name is = '+directory1
  echo 'exist value is = '+exist
  echo "2. ----------------------------------------"
  File directory2 = new File('.\\ABC')
  exist = directory2.exists()
  echo 'Directory2 name is = '+directory2
  echo 'exist value is = '+exist
  echo "3. ----------------------------------------"  
  File directory3 = new File(dir)
  exist = directory3.exists()
  echo 'Directory3 name is = '+directory3
  echo 'exist value is = '+exist
  echo "4. Pipeline Syntax ------------------------"  
  exist = fileExists '.\\ABC'
  echo 'exist value is = '+exist
  echo "5. ----------------------------------------"
  File directory5 = new File(dir)
  echo 'Directory5 name is = '+directory5
  // execute an error
  // exist = fileExists(directory5)
  exist = fileExists "directory5"
  echo 'exist value is = '+exist
  echo "6. ----------------------------------------"
  exist = fileExists(dir)
  echo 'exist value is = '+exist

  File[] listFiles = directory5.listFiles()
  echo 'List file = '+listFiles

And the Output in the Jenkins Console Output is: (I cleaned it a little bit up….)

1. ----------------------------------------
Directory1 name is = .\ABC\
exist value is = false
2. ----------------------------------------
Directory2 name is = .\ABC
exist value is = false
3. ----------------------------------------
Directory3 name is = .\ABC
exist value is = false
4. Pipeline Syntax ------------------------
exist value is = true
5. ----------------------------------------
Directory5 name is = .\ABC
exist value is = false
6. ----------------------------------------
exist value is = true

List file = null

I only get a true value in step 4 and 6. So I can be sure that the folder really exist.

So it seems to be for me that the command:

File directory = new File(dir)

Not work correct in my case.

I can’t create a "listFile" variable because the directory would not be initialized correct.

For me is also not clear which kind of commands I should use. The groovy examples use always functions like:


But in the Jenkins examples I always find code like this:


Why there are some differences between groovy and Jenkins groovy style? It should be the same ore not?

Does anyone have an idea for me or can told me what I’m doing wrong?

You can add below script to list the file and folders in current work directory, so that you can confirm the folder ABC is exists or not.

After you confirm the ABC folder exist, then dig into the rest code.

def deleteFilesOlderThanDays() {

  // print current work directory

  // if jenkins job run on window machine
  bat 'dir'

  // if jenkins job run on linux machine    
  sh 'ls -l'

  dir = '.\\ABC'
  echo "1. ----------------------------------------"

For fileExists usage, I think the correct way as following:

fileExists './ABC'

def dir = './ABC'
fileExists dir

Should use / as path separator, rather than \ according to its document at below:

File.exists() in a Jenkins groovy file do not work - jenkins - java, In the basic Jenkins file I execute the function “file.deleteFilesOlderThanDays()” ( for testing I do not use any parameters). The code from my function for testing is:� Pipeline supports two syntaxes, Declarative (introduced in Pipeline 2.5) and Scripted Pipeline.Both of which support building continuous delivery pipelines. Both may be used to define a Pipeline in either the web UI or with a Jenkinsfile, though it’s generally considered a best practice to create a Jenkinsfile and check the file into the source control repository.

You may benefit from this answer from a similar question:

" methods will refer to files on the master where Jenkins is running, so not in the current workspace on the slave machine.

To refer to files on the slave machine, you should use the readFile method "

def dir = readFile("${WORKSPACE}/ABC");

Link to original answer

Pipeline with conditional stages based on a file existing on the , Issue. I would like to have a Jenkins Pipeline that will conditionally run specific stages depending if a file exists on the filesystem. 'true' } } steps { echo "file exists" } } stage('conditional if not exists'){ when { expression { MY_FILE == 'false' } } steps { echo "file does not exist" } } } } Pipeline: Groovy 2.65� I want to migrate to Jenkins 2.8, switching from JobDSL v1.34 to v1.47. I am using a Groovy script to do set up a tailored environment for the JobDSL file (binding + new GroovyShell + running the DSL file there). It used to work fine with v1.34, including a workaround mentioned below.

Thanks for all that feedback.

OK, for me is now clear that Jenkins Groovy != Groovy is. I have read a lot about it that there are different command if you are executing file search on a Jenkins Master or on a Jenkins Slave.

The suggestion from Youg to start after confirmation helps me. I had problems with deleting the file so at the end I used a primitive batch command to get my function run.

The finally functions looks like now:

def deleteFilesOlderThanXDays(daysBack, path) {

  def DAY_IN_MILLIS = 24 * 60 * 60 * 1000

    // change into path
    dir(path) {

      // find all kind of files
    files = findFiles(glob: '*.*')

    for (int i = 0; i < files.length; i++) {

      def days_from_now = ( (System.currentTimeMillis() - files[i].lastModified) /(DAY_IN_MILLIS))

      if(days_from_now > daysBack) {
        echo('file : >>'+files[i].name+'<< is older than '+daysBack+' days')
        bat('del /F /Q "'+files[i].name+'"')
          echo('file : >>'+files[i].name+'<< is not only than '+daysBack+' days')
      }// End: for (int i = 0; i < files.length; i++) {
    }// End: dir(path) {
  }// End: if(fileExists(path)){

Thanks for helping and best regards,

Pipeline: Basic Steps, job with a Jenkins files that has the following content.. but I can't get controlFile to work correctly as it is a variable and fileExists doesnt seem� Piotr Krukowiecki added a comment - 2020-04-15 20:15 - edited This seems to be not only affecting shared libraries, but any groovy code. For example using File class in "script" block and checking if file exists does not work.

[JENKINS-38972] fileExists doesn't take variables, file cannot be opened - assume it does not exist # AutoHotkey's FileExist() function returns an attribute string (a subset of "RASHNDOCT") if a� I am using groovy to create a file like "../A/B/file.txt". To do this, I have created a service and pass the file path to be created as an argument. This service is then used by a Job. The Job will do the logic in creating the file in the specified directory. I have manually created the "A" directory.

Check that file exists, handle wildcards? I have created a zip file in the workspace folder in advance. FileExists() does not support wildcards. FileFindFirst() does� You can't really make use of the new File and normal Groovy/Java ways to traverse file systems. The call is security checked by default (see JENKINS-38131) and won't even generally work because of how Jenkins Pipelines executes your pipeline code.

Is it possible for the Jenkins pipeline function 'fileExist' to handle , We can test and check if a file exist or not by using the PowerShell cmdlet groovy script through a jenkins job, the latest groovy plugin (v2)doesn't work. Delete() call , we have added a validation method on file name but that didn't worked. If file is not found, print "file not found". I was given 2 hours time to do it and I could use the internet. As I had no idea what groovy was or json was, I searched it and set up groovy but could not obtain the output in two hours.

  • Jenkins Groovy != Groovy. The Jenkins Groovy language is a specialized compiler and runtime for Groovy source that does not behave exactly like normal Groovy execution. This comment can be helpful, as well as possibly my answer to this question.