[英]Bash script loop through subdirectories and write to file without using find,ls etc
很抱歉再次提出这个问题。 我已经收到了答案,但是使用了find
但是不幸的是,我需要在不使用任何预定义命令的情况下编写它。
我正在尝试编写一个脚本,该脚本将循环遍历当前目录中的子目录。 它应该检查每个目录中的文件数。 如果文件数大于10,则应在“ BigList”文件中写入这些文件的所有名称,否则应在“ ShortList”文件中写入。 看起来应该像这样:
---<directory name>
<filename>
<filename>
<filename>
<filename>
....
---<directory name>
<filename>
<filename>
<filename>
<filename>
....
我的脚本仅在子目录没有依次包含子目录的情况下才有效。 我对此感到困惑,因为它无法按我预期的那样工作。 这是我的剧本
#!/bin/bash
parent_dir=""
if [ -d "$1" ]; then
path=$1;
else
path=$(pwd)
fi
parent_dir=$path
loop_folder_recurse() {
local files_list=""
local cnt=0
for i in "$1"/*;do
if [ -d "$i" ];then
echo "dir: $i"
parent_dir=$i
echo before recursion
loop_folder_recurse "$i"
echo after recursion
if [ $cnt -ge 10 ]; then
echo -e "---"$parent_dir >> BigList
echo -e $file_list >> BigList
else
echo -e "---"$parent_dir >> ShortList
echo -e $file_list >> ShortList
fi
elif [ -f "$i" ]; then
echo file $i
if [ $cur_fol != $main_pwd ]; then
file_list+=$i'\n'
cnt=$((cnt + 1))
fi
fi
done
}
echo "Base path: $path"
loop_folder_recurse $path
如何修改脚本以产生所需的输出?
此bash脚本产生所需的输出:
#!/bin/bash
bigfile="$PWD/BigList"
shortfile="$PWD/ShortList"
shopt -s nullglob
loop_folder_recurse() {
(
[[ -n "$1" ]] && cd "$1"
for i in */; do
[[ -d "$i" ]] && loop_folder_recurse "$i"
count=0
files=''
for j in *; do
if [[ -f "$j" ]]; then
files+="$j"$'\n'
((++count))
fi
done
if ((count > 10)); then
outfile="$bigfile"
else
outfile="$shortfile"
fi
echo "$i" >> "$outfile"
echo "$files" >> "$outfile"
done
)
}
loop_folder_recurse
shopt -s nullglob
,以便在目录为空时不会运行循环。 函数的主体位于( )
之内,因此它可以在子shell中运行。 这是为了方便起见,因为这意味着当子shell退出时,该函数返回到先前的目录。
希望脚本的其余部分很容易解释,但如果不是这样,请告诉我,我很乐意提供其他解释。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.