递归计算特定文件 BASH

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6268863/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 00:08:26  来源:igfitidea点击:

Recursively count specific files BASH

bashrecursionfile-type

提问by jamesy

My goal is to write a script to recursively search through the current working directory and the sub dirctories and print out a count of the number of ordinary files, a count of the directories, count of block special files, count of character special files,count of FIFOs, and a count of symbolic links. I have to use condition tests with [[ ]]. Problem is I am not quite sure how to even start.

我的目标是编写一个脚本来递归搜索当前工作目录和子目录,并打印出普通文件数、目录数、块特殊文件数、字符特殊文件数、计数FIFO 的数量,以及符号链接的数量。我必须对 [[]] 使用条件测试。问题是我不太确定如何开始。

I tried the something like the following to search for all ordinary files but I'm not sure how recursion exactly works in BASH scripting:

我尝试了以下类似的方法来搜索所有普通文件,但我不确定递归在 BASH 脚本中究竟是如何工作的:

function searchFiles(){
    if [[ -f /* ]]; then
        return 1
    fi
}
searchFiles
echo "Number of ordinary files $?"

but I get 0 as a result. Anyone help on this?

但结果我得到了 0。有人帮忙解决这个问题吗?

回答by MattH

Why would you not use find?

你为什么不使用find

$ # Files
$ find . -type f | wc -l
327
$ # Directories
$ find . -type d | wc -l
64
$ # Block special
$ find . -type b | wc -l
0
$ # Character special
$ find . -type c | wc -l
0
$ # named pipe
$ find . -type p | wc -l
0
$ # symlink
$ find . -type l | wc -l
0

回答by Fredrik Pihl

Something to get you started:

一些让你开始的东西:

#!/bin/bash

directory=0
file=0
total=0

for a in *
do
   if test -d $a; then
      directory=$(($directory+1))
   else
      file=$(($file+1))
   fi

   total=$(($total+1))
   echo $a

done

echo Total directories: $directory
echo Total files: $file
echo Total: $total

No recursion here though, for that you could resort to ls -lRor similar; but then again if you are to use an external program you should resort to using find, that's what it's designed to do.

不过这里没有递归,因为你可以求助于ls -lR或类似的方法;但话说回来,如果您要使用外部程序,您应该求助于 using find,这就是它的设计目的。