所以我正在尝试编写一个 bash 脚本,该脚本将查看指定文件夹中的所有子目录,并返回单个子目录中的最大文件数。这是我现在拥有的:
#!/bin/bash
maxCount=0
fileCount=0
# script that writes out all the directories and how many files are in each directory
find ./testdata/ -maxdepth 1 -mindepth 1 -type d | while read dir; do #loop all subdirectories
fileCount= find "$dir" -type f | wc -l #count all the files in subdirectory
if [ $fileCount -gt $maxCount ] #if the count is higher than the max
then
maxCount= "$fileCount" #set the count equal to the max
fi
done
#print out how many messages are in the thread
echo "$maxCount"
首先,变量 fileCount 设置不正确。 find "$dir"-type f | 的输出wc -l 仍被设置为标准输出,因此脚本不断返回零。
当前输出示例:
1
1
2
1
1
1
0
最后一个零是 echo "$maxCount"的输出
不太确定我做错了什么。谢谢!
使用 xfce4 终端
最佳答案
你可以用下面的命令做你想做的,它利用了 find
的 -exec
选项
find ./testdata/ -maxdepth 1 -mindepth 1 -type d -exec bash -c 'find {} -type f | wc -l' \; | sort -n | tail -n 1
按照您的方法,这一行
fileCount= find "$dir" -type f | wc -l #count all the files in subdirectory
=
和find
之间不应该有空格并且你应该有一个Command Substitution将值分配给变量 fileCount
,如下所示:
fileCount=$(find "$dir" -type f | wc -l)
如果你想坚持 for 循环:
find . -maxdepth 1 -mindepth 1 -type d | while read dir;do
cnt=$(find ${dir} -type f | wc -l)
echo ${cnt}
done | sort -n | tail -n 1
关于bash - 查找子目录中的最大文件数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46901269/