linux - 使用 shell 脚本统计文件和目录

标签 linux bash shell unix scripting

我正在学习 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/

相关文章:

linux - 需要帮助在 shell 脚本中查找 PID

linux - 如何在 bash shell 脚本中添加另一个 "for"循环?

bash - bash 中 while 循环中的实数

linux - 使用字符串输入查找文件名的 Shell 脚本

bash - 如何在 Perl 中转义 <<() 习惯用法

c - C语言中如何使用管道连接两个子进程

android - 当我的 nexus 6p 处于恢复模式时,ADB 无法列出我的设备

linux - 如何终止 webshel​​l 上的 ping?

windows - 在 PATH 环境中拥有本地目录不安全?

linux - Bash:检测所有磁盘并显示可用空间