首页 > 解决方案 > bash - 每个目录的文件数和最后的总数

问题描述

带有 bash 4.4.20 的 Ubuntu 18.04 LTS

我正在尝试从执行脚本的目录开始计算每个目录中的文件数。借用其他编码人员,我找到了这个脚本并对其进行了修改。我正在尝试修改它以在最后提供总数,但我似乎无法得到它。此外,该脚本在每个循环中运行两次相同的计数函数,效率低下。我插入了那个额外的 find 命令,因为我无法获得嵌套的结果find | wc -l ' 存储在变量中。它仍然没有工作。

谢谢!

#!/bin/bash

count=0
find . -maxdepth 1 -mindepth 1 -type d | sort -n | while read dir; do
  printf "%-25.25s : " "$dir"
  find "$dir" -type f | wc -l
  filesthisdir=$(find "$dir" -type f | wc -l)
  count=$count+$filesthisdir
done

echo "Total files : $count"

这是结果。它应该汇总结果。否则,这将运作良好。

./1800wls1                : 1086
./1800wls2                : 1154
./1900wls-in1             : 780
./1900wls-in2             : 395
./1900wls-in3             : 0
./1900wls-out1            : 8
./1900wls-out2            : 304
./1900wls-out3            : 160
./test                    : 0
Total files : 0

标签: linuxbashfind

解决方案


这不起作用,因为while循环是在子 shell 中执行的。通过使用<<<,您可以确保它在当前 shell 中执行。

#!/bin/bash

count=0
while read dir; do
  printf "%-25.25s : " "$dir"
  find "$dir" -type f | wc -l
  filesthisdir=$(find "$dir" -type f | wc -l)
  ((count+=filesthisdir))
done <<< "$(find . -maxdepth 1 -mindepth 1 -type d | sort -n)"

echo "Total files : $count"

当然你也可以使用 for 循环:

for i in "$(find . -maxdepth 1 -mindepth 1 -type d | sort -n)"; do
  # do something
done

推荐阅读