You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Jenkins Pipeline脚本中列出指定目录的所有子目录

在Jenkins Pipeline中获取指定目录的所有子目录

嘿,这个需求我之前在项目里刚好处理过,Jenkins Pipeline里有两种很实用的实现方式,我给你详细说说:

方法1:用Shell命令(简单直接,适合Linux/macOS环境)

如果你的Jenkins跑在类Unix系统上,直接调用shell的find命令是最快捷的方式,通过sh步骤捕获输出就行。

示例代码(获取一级子目录)

pipeline {
    agent any
    stages {
        stage('Fetch Subdirectories') {
            steps {
                script {
                    // 替换成你实际要查询的目录路径
                    def targetDir = '/var/jenkins_home/workspace/your-project/target-folder'
                    
                    // 用find命令筛选一级子目录,排除目录本身
                    def subdirList = sh(
                        script: "find ${targetDir} -maxdepth 1 -type d ! -path ${targetDir}",
                        returnStdout: true
                    ).trim().split('\n')
                    
                    // 打印结果验证
                    echo "找到的一级子目录:"
                    subdirList.each { dir ->
                        echo "- ${dir}"
                    }
                }
            }
        }
    }
}
  • 要是需要递归获取所有嵌套子目录,删掉命令里的-maxdepth 1就行。
  • 如果路径里有空格或特殊字符,记得给${targetDir}加双引号:find "${targetDir}" ...

方法2:用Groovy原生File API(跨平台友好)

如果你的Jenkins需要兼容Windows和类Unix系统,用Groovy的File类更稳妥,不需要担心shell命令的差异,纯Groovy代码就能搞定。

示例代码(获取一级子目录)

pipeline {
    agent any
    stages {
        stage('Fetch Subdirectories') {
            steps {
                script {
                    def targetDir = new File('/var/jenkins_home/workspace/your-project/target-folder')
                    
                    // 先校验目录是否合法
                    if (!targetDir.exists() || !targetDir.isDirectory()) {
                        error "指定路径不存在或不是目录:${targetDir.path}"
                    }
                    
                    // 过滤出所有一级子目录,收集完整路径
                    def subdirList = targetDir.listFiles().findAll { it.isDirectory() }.collect { it.path }
                    
                    // 要是需要递归获取所有子目录,换成下面的代码:
                    // def allSubdirs = []
                    // targetDir.eachFileRecurse(FileType.DIRECTORIES) { dir ->
                    //     allSubdirs << dir.path
                    // }
                    
                    // 打印结果
                    echo "找到的一级子目录:"
                    subdirList.each { dir ->
                        echo "- ${dir}"
                    }
                }
            }
        }
    }
}

几个需要注意的点

  • 权限问题:Jenkins运行的用户(比如默认的jenkins用户)必须对目标目录有读取权限,否则会返回空列表或者报错。
  • 远程节点:如果agent是远程节点,要确保远程节点上的用户能访问目标目录,路径要对应远程节点的本地路径。
  • 空目录处理:如果目标目录下没有子目录,两种方法都会返回空数组,记得在后续逻辑里做判空处理。

内容的提问来源于stack exchange,提问作者Pankaj Shinde

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 05:08:12