【问题标题】:Recursively count directories and files with a shell script使用 shell 脚本递归地计算目录和文件
【发布时间】:2025-01-06 15:50:01
【问题描述】:

我正在尝试编写一个 shell 脚本,它将递归地计算目录中的所有文件和子目录以及所有隐藏的文件和子目录。我的脚本可以计算它们,但是它无法检测到子目录中的隐藏文件和目录。我怎样才能改变它,使它能够做到这一点?我也不能使用 find、du 或 ls -R

#!/bin/bash
cd $1
dir=0
hiddendir=0
hiddenfiles=0
x=0
items=( $(ls -A) )
amount=( $(ls -1A | wc -l) )

counter() {
    if [ -d "$i" ]; then
        let dir+=1
        if [[ "$i" == .* ]]; then
            let hiddendir+=1
            let dir-=1
        fi
        search "$i"
    elif [ -f "$i" ]; then
        let files+=1
        if [[ "$i" == .* ]]; then
            let files-=1
            let hiddenfiles+=1
        fi
    fi
}
search() {
    for i in $1/*; do
        counter "$i"
    done
}
while [ $x -lt $amount ]; do
    i=${items[$x]}
    counter "$i"
    let x+=1
done

【问题讨论】:

    标签: bash shell recursion


    【解决方案1】:
    #!/bin/bash -e
    
    shopt -s globstar dotglob # now ** lists all entries recursively
    
    cd "$1"
    
    dir=0 files=0 hiddendir=0 hiddenfiles=0
    
    counter() {
       if [ -f "$1" ]; then local typ=files
       elif [ -d "$1" ]; then local typ=dir
       else continue
       fi
       [[ "$(basename "$1")" == .* ]] && local hid=hidden || local hid=""
       ((++$hid$typ))
    }
    
    for i in **; do
       counter "$i"
    done
    
    echo $dir $files $hiddendir $hiddenfiles
    

    【讨论】:

    • 你真的在使用expreval吗?你真的在现实生活中每天都这样做吗?有#!/bin/bashshebang?认真的吗?
    • 1. Yes. 2. a) 是的。 b) 没有。3. 是。 4.是的。
    • 谢谢,但这与我的做法相反。只能看到原目录中的隐藏文件,但是如果有隐藏目录,那里面的子目录和文件肯定都被隐藏了吧?
    • 我真的试过了。它计算可见目录、可见文件、隐藏目录和隐藏文件。隐藏目录中的可见条目被视为可见。例如,相对于 $1,.dir 是隐藏的,.dir/dir 是可见的,.dir/.file 是隐藏的。它们都被计算在内。
    【解决方案2】:

    考虑使用这个:

    find . | wc -l
    

    【讨论】:

    • 简短而优雅。 Sam 似乎受制于这种情况:cannot use find, du or ls -R。除非山姆对这些命令过敏或受宗教誓言约束,否则我想这是山姆应该做的某种家庭作业。