Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to list all directories from within directory in jenkins pipeline script

I want to get all directories present in particular directory from jenkins pipeline script.

How can we do this?

like image 231
Pankaj Shinde Avatar asked Apr 29 '19 11:04

Pankaj Shinde


People also ask

How do I get a list of pipelines in Jenkins?

On the Manage Jenkins page for your installation, navigate to Manage Plugins. Find Pipeline Plugin from among the plugins listed on the Available tab. (You can do this by scrolling through the plugin list or by using “Pipeline” as a term to filter results) Select the checkbox for Pipeline Plugin.

What does DIR do in Jenkinsfile?

dir : Change current directory.


2 Answers

If you want a list of all directories under a specific directory e.g. mydir using Jenkins Utility plugin you can do this:

Assuming mydir is under the current directory:

 dir('mydir') {
   def files = findFiles() 
 
   files.each{ f -> 
      if(f.directory) {
        echo "This is directory: ${f.name} "
      }
   }
 }

Just make sure you do NOT provide glob option. Providing that makes findFiles to return file names only.

More info: https://jenkins.io/doc/pipeline/steps/pipeline-utility-steps/

like image 60
xbmono Avatar answered Sep 18 '22 05:09

xbmono


I didn't find any plugin to list folders, so I used sh/bat script in pipeline, and also this will work irrespective of operating system.

pipeline {
  stages {
    stage('Find all fodlers from given folder') {
      steps {
        script {
                    
          def foldersList = []
                    
          def osName = isUnix() ? "UNIX" : "WINDOWS"
          echo "osName: " + osName
    
          echo ".... JENKINS_HOME: ${JENKINS_HOME}"
    
          if(isUnix()) {
            def output = sh returnStdout: true, script: "ls -l ${JENKINS_HOME} | grep ^d | awk '{print \$9}'"
            foldersList = output.tokenize('\n').collect() { it }
          } else {
            def output = bat returnStdout: true, script: "dir \"${JENKINS_HOME}\" /b /A:D"
            foldersList = output.tokenize('\n').collect() { it }
            foldersList = foldersList.drop(2)
                     
          }
          echo ".... " + foldersList
        }            
      }
    }
  }
}
like image 40
Pankaj Shinde Avatar answered Sep 19 '22 05:09

Pankaj Shinde