我正在构建一个小型 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."
这是到目前为止我的代码,我在执行它时给出了路径,但它为我找到了它找到的任何文件夹提供了结果。那么我怎样才能停止这个循环呢? 谢谢。
最佳答案
使用find .
引用联机帮助页
-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.
有一点find ,GNU awk ,和sort ,您可以以*安全的方式做您想做的事。
#!/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/