linux - 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
解决方案
这不起作用,因为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
推荐阅读
- javascript - 我们如何在 JavaScript 中使用具有多个条件的三元运算符?
- swift - 为 xcode 项目安装 webMIDIKit
- python - 运行 Python 的必要模块是什么?(对于 PyInstaller)
- python - Python Gmail IMAP 在某个日期之后
- javascript - 在另一个组件中单击时反应打开的模式窗口
- javascript - 在 Angular 中修改 json
- python-3.x - 为什么要打开 openAI 健身房?
- npm - 链接的密钥无效
- php - 让 libphonenumber 与 autoloader.php 一起工作的问题
- android - 启用 proguard 后 JNI 检测到错误导致应用程序崩溃