Skip to content

Instantly share code, notes, and snippets.

@tamasgal
Created May 29, 2018 15:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tamasgal/e520784a2e58ea4a3300f9c0e3cfa323 to your computer and use it in GitHub Desktop.
Save tamasgal/e520784a2e58ea4a3300f9c0e3cfa323 to your computer and use it in GitHub Desktop.
Getting a list of filenames in a given directory
#!groovy
import static groovy.io.FileType.FILES
node('master') {
FILES_DIR = './foo'
cleanWs()
sh """
mkdir foo
touch foo/bar1
touch foo/bar2
touch foo/bar3
"""
def filenames = [];
def dir = new File("${env.WORKSPACE}/${FILES_DIR}");
dir.traverse(type: FILES, maxDepth: 0) {
filenames.add(it.getName())
}
for (int i = 0; i < filenames.size(); i++) {
def filename = filenames[i]
echo "${filename}"
}
}
@tamasgal
Copy link
Author

This produces the following output (only lists bar1):

Started by user Tamas Gal
Running in Durability level: MAX_SURVIVABILITY
[Pipeline] node
Running on Jenkins in /var/lib/jenkins/workspace/TestHome
[Pipeline] {
[Pipeline] cleanWs
[WS-CLEANUP] Deleting project workspace...[WS-CLEANUP] done
[Pipeline] sh
[TestHome] Running shell script
+ mkdir foo
+ touch foo/bar1
+ touch foo/bar2
+ touch foo/bar3
[Pipeline] echo
bar1
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS

@tamasgal
Copy link
Author

OK, this one works. Ridiculous...

#!groovy

node('master') {
    FILES_DIR = './foo'
    cleanWs()
    
    sh """
        mkdir foo
        touch foo/bar1
        touch foo/bar2
        touch foo/bar3
    """

    def TMP_FILENAME = ".docker_files_list"
    sh "ls ${FILES_DIR} > ${TMP_FILENAME}"
    def filenames = readFile(TMP_FILENAME).split( "\\r?\\n" );
    sh "rm -f ${TMP_FILENAME}"

    for (int i = 0; i < filenames.size(); i++) {
        def filename = filenames[i]
        echo "${filename}"
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment