【发布时间】:2017-10-24 02:30:15
【问题描述】:
所以我正在尝试编写一个 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 终端
【问题讨论】:
-
由于
while循环在一个新的子shell中执行,一旦循环终止,内部使用的变量将不可用 -
@etopylight 那么我怎样才能保留变量值呢?
-
一个简单的解决方法是使用命令分组,它使用花括号使这些命令和变量在同一范围内共存,例如
{while read dir; ... echo "$maxCount"}应该可以工作跨度> -
抱歉打错了代码,正确的例子应该是
{ while read dir; ... echo "$maxCount"; },注意{和while之间需要额外的空格以及最后一个命令和}之间的分号 -
很高兴为您提供帮助:)
标签: bash unix subdirectory