我正在学习 bash 脚本并编写了一个脚本来计算作为参数提供的目录中的文件和目录。我让它以一种对我来说很奇怪的方式工作,我想知道是否有更简单的方法。
我已经注释掉了可以运行的代码,但将其保留作为比较。我试图让 for
循环工作,而不是在其中使用 if
语句来检测给定位置中的项目是文件还是目录。
编辑:我刚刚发现注释代码也计算给定位置子目录中的所有文件和目录!有什么办法可以防止这种情况,只计算给定位置的文件和目录?
#!/bin/bash
LOCATION=$1
FILECOUNT=0
DIRCOUNT=0
if [ "$#" -lt "1" ]
then
echo "Usage: ./test2.sh <directory>"
exit 0
fi
#DIRS=$(find $LOCATION -type d)
#FILES=$(find $LOCATION -type f)
#for d in $DIRS
#do
# DIRCOUNT=$[$DIRCOUNT+1]
#done
#for f in $FILES
#do
# FILECOUNT=$[$FILECOUNT+1]
#done
for item in $LOCATION
do
if [ -f "$item" ]
then
FILECOUNT=$[$FILECOUNT+1]
elif [ -d "$item" ]
then
DIRCOUNT=$[$DIRCOUNT+1]
fi
done
echo "File count: " $FILECOUNT
echo "Directory count: " $DIRCOUNT
出于某种原因,无论我将位置指向何处,for
循环的输出总是返回:
File count: 0 , Directory count: 1
最佳答案
使用 find
如下所示。该解决方案将正确计算带有空格、换行符和点文件的文件名。
FILECOUNT="$(find . -type f -maxdepth 1 -printf x | wc -c)"
DIRCOUNT="$(find . -type d -maxdepth 1 -printf x | wc -c)"
请注意,DIRCOUNT
包括当前目录 (.
)。如果您不想这样做,请减去 1。
((DIRCOUNT--)) # to exclude the current directory
关于linux - 使用 shell 脚本统计文件和目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13727069/