首页 > 解决方案 > 用户有没有办法指定我的脚本将搜索多少个文件夹级别?

问题描述

我正在构建一个小型 bash 脚本项目。我的代码有 2 个参数,一个搜索路径和一个告诉我必须分析多少文件夹级别的数字。例如,如果用户给我的程序编号为 2,它必须搜索其中的所有目录以及其中的所有目录。

#!/bin/bash

function check_dir {
    echo Checking dir : $1
    for f in `ls $1`
    do
        if [ -d $1/$f ]
        then
            dirs_num=$(($dirs_num+1))
            check_dir $1/$f
        else    
            files_num=$(($files_num+1))
            size=`stat -c%s $1/$f`
            echo $1/$f - $size
        fi
    done
}

files_num=0
dirs_num=0
depth=$2
check_dir $1
echo "Found $files_num files and $dirs_num dirs."

到目前为止,这是我的代码,我在执行它时给出了路径,但它给了我找到的任何文件夹的结果。那么我该如何停止这个循环呢?谢谢你。

标签: bash

解决方案


使用

引用手册页

 -maxdepth levels
       Descend at most levels (a non-negative integer) levels of directories
       below  the command line  argu‐ments.  -maxdepth 0  means only apply the
       tests and actions to the command line arguments.

通过一些、 GNU ,您可以以*安全的方式做您想做的事。

#!/bin/bash

awk '
  BEGIN{ RS="\0" } # Non-portable, requires GNU awk
  $1 != dir{
        print "Checking dir : " $1
        dcnt++
        dir = $1
  }
  {
        print $1$2 " - " $3
        fcnt++
  }
  END{
        print "Found " fcnt " files and " dcnt " dirs."
  }' <(find "$1" -maxdepth "$2" -type f -printf "%h\t%f\t%s\0" | LC_ALL=C sort -z )

*safe 我的意思是每条记录都被 NUL 终止并且不解析ls


推荐阅读