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.
通过一些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 )
*safe 我的意思是每条记录都被 NUL 终止并且不解析ls
推荐阅读
- python - Python Web-scraping,类别提取
- python - 我如何避免在 linux 上的 chromium 中检测硒?
- c++ - ':' - 类构造函数中的运算符
- spring-integration - 如何暂停Spring云数据流Source类向kafka发送数据?
- deployment - 如何在 AKS 中部署 ff4j 服务器?
- microsoft-graph-api - 使用 Graph 的 sendActivityNotification 时未收到团队通知
- pytorch - 如何检查小张量是否在大张量内
- google-play-console - Google Play Console 如何在 beta 后发布我的应用
- r - 具有正交多项式预测器的模型中的系数如何工作?
- angular - Angular Material 将初始焦点设置在没有点击事件的表单控件上