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

Bash中获取目录文件/文件夹数量与名称的问题及解决

Bash 统计文件/文件夹数量及数组存储方案

1. 正确统计文件、文件夹数量的方法

递归统计(含子目录)

用 find 结合 wc 是最可靠的递归统计方式:

  • 统计所有文件(包括子目录内的文件):
    file_count=$(find ./test_dir -type f | wc -l)
    echo "文件总数:$file_count"
    
  • 统计所有文件夹(包含目标目录本身):
    folder_count=$(find ./test_dir -type d | wc -l)
    echo "文件夹总数:$folder_count"
    
  • 若需排除目标目录本身,仅统计子文件夹:
    folder_count=$(find ./test_dir -mindepth 1 -type d | wc -l)
    

仅统计当前目录(不含子目录)

如果不需要递归,用 Bash glob 更高效:

  • 文件数量:
    shopt -s nullglob  # 避免目录为空时返回(*)字符串
    file_count=(*)
    file_count=${#file_count[@]}
    
  • 文件夹数量:
    shopt -s nullglob
    folder_count=(*/)
    folder_count=${#folder_count[@]}
    

2. 存入数组并通过数组大小计数

完全可以,还能同时保留所有文件/文件夹的路径。分两种场景处理:

安全存储(支持含空格、特殊字符的文件名)

这种写法能避免特殊字符导致的数组元素拆分错误:

# 存储所有文件到数组
readarray -d '' files < <(find ./test_dir -type f -print0)
# 数组长度即为文件数量
file_count=${#files[@]}

# 存储所有文件夹到数组
readarray -d '' folders < <(find ./test_dir -type d -print0)
folder_count=${#folders[@]}

其中 -print0 让 find 用空字符分隔路径,readarray -d '' 对应读取空分隔的内容,完美兼容特殊文件名。

简化写法(文件名无特殊字符)

如果确定文件名不含空格、引号等特殊字符,可使用简化写法:

files=($(find ./test_dir -type f))
file_count=${#files[@]}

folders=($(find ./test_dir -type d))
folder_count=${#folders[@]}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 07:36:20