'How to list the sub directory and the result load as an array component from groovy Jenkins script
def clusterComponent = "components/"
//from below listed the sub folder in components/ directory
stage('list components') {
sh("ls -A1 ${clusterComponent}")
}
I want to load the list result to clustercomponent as an array. example output should be clusterComponent = ["item1", "item2", "item3", "item4"]
maybe this is not the proper way. Still a beginner at groovy scripting.
Solution 1:[1]
If you want to save the output of the sh step to a variable, you need to use returnStdout: true. Then you want to have each line of the output as a separate entry in the array/list, so you need to .split('\n') - split the string by the newline character.
The script can be:
def clusterComponent = "components/"
//from below listed the sub folder in components/ directory
stage('list components') {
List<String> files = sh(script: "ls -A1 ${clusterComponent}", returnStdout: true).trim().split('\n')
}
You can also avoid the sh step to do this task and use the findFiles step from pipeline-utility-steps. This returns a FileWrapper class instance, so if you need the file name only, you can use:
def clusterComponent = "components/"
//from below listed the sub folder in components/ directory
stage('list components') {
List<String> files = findFiles(glob: "${clusterComponent}/*").collect { file -> file.name }
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | VANAN |
