bash - 有没有办法让用户指定我的脚本将搜索多少个文件夹级别?

标签 bash

我正在构建一个小型 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."

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

最佳答案

使用 .

引用联机帮助页

 -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 )

通过*安全我的意思是每条记录都是NUL终止的并且doesn't parse ls

关于bash - 有没有办法让用户指定我的脚本将搜索多少个文件夹级别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62266368/

相关文章:

string - 从 bash 中的字符串中提取电子邮件字符串

linux - 从我的环境中删除错误的路径

bash - sudo echo "something">>/etc/privilegedFile 不起作用

bash - ffmpeg 脚本 mp4 到 mp3

linux - Bash:将程序输出的每一行重定向到实时文件

bash - 如何通过 sudo 命令使用 for 循环运行脚本

linux - 为什么通配符在 if 子句 bash 中不起作用

linux - shell脚本获取列数据

java - 使用 SwingWorker/Swing 跟踪 wget (bash) 的进度

macos - 在 Mac OS X 上的 bash 中更改 $IFS