[英]How can I recursively count the number of each type of file in a unix directory without using find or -type?
I am attempting to count the number of regular files, subdirectories, symbolic links, block special files, and character special files that are contained in a directory in unix, but each time I try I get inconsistent results. 我试图计算unix目录中包含的常规文件,子目录,符号链接,块特殊文件和字符特殊文件的数量,但是每次尝试都会得到不一致的结果。 I consistently get results for normal files, but never the same number, and none of the others stay the same either.
我始终能获得普通文件的结果,但是从来没有相同的数字,其他任何一个都保持不变。 I have attached the script I am trying to use right now.
我已经附上了我现在尝试使用的脚本。 The proper usage for the script can be seen in the error message that checks for the correct input.
可以在检查正确输入的错误消息中看到脚本的正确用法。
userinput=$1
#makes sure that there is only one input
if [ $# -ne 1 ];
then
echo "Usage: dircount.sh directory" 1>&2
exit 0
fi
#makes sure the file is a readable directory
if [ ! -d "$userinput" ] || [ ! -r "$userinput" ];
then
echo "Please enter a directory you can read" 1>&2
exit 0
else
#prints the current directory
cd $userinput
pwd
regfiles=0
numsubs=0
numsymb=0
numblock=0
numspecial=0
for file in `ls -l $*`
do
if [ -f "$file" ];
then
regfiles=`expr 1 + $regfiles`
fi
if [ -d "$file" ];
then
numsubs=`expr 1 + $numsubs`
fi
if [ -L "$file" ];
then
numsymb=`expr 1 + $numsymb`
fi
if [ -b "$file" ];
then
numblock=`expr 1 + $numblock`
fi
if [ -c "$file" ];
then
numspecial=`expr 1 + $numspecial`
fi
done
Don't parse ls
. 不要解析
ls
。 Use bash's recursive globbing 使用bash的递归遍历
shopt -s globstar nullglob
for file in **; do ...
I would use an associative array to hold the counts 我将使用关联数组来保存计数
declare -A num
for file in **; do
[[ -f $file ]] && (( num["reg"]++ ))
Something like the next can work (need bash4). 诸如此类的东西可以工作(需要bash4)。
declare -A SUMTYPES
while read -r type
do
let SUMTYPES["$type"]++
done < <(stat -c "%F" *) #this is for gnu version of "stat"
for i in "${!SUMTYPES[@]}"
do
echo "${SUMTYPES[$i]} $i"
done
produces for example the next output 产生例如下一个输出
1 regular empty file
5 directory
1 symbolic link
9 regular file
1 fifo
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.