[英]Bash script loop through subdirectories and write to file without using find,ls etc
Sorry for asking this question again. 很抱歉再次提出这个问题。 I have already received answer but with using
find
but unfortunately I need to write it without using any predefined commands. 我已经收到了答案,但是使用了
find
但是不幸的是,我需要在不使用任何预定义命令的情况下编写它。
I am trying to write a script that will loop recursively through the subdirectories in the current directory. 我正在尝试编写一个脚本,该脚本将循环遍历当前目录中的子目录。 It should check the file count in each directory.
它应该检查每个目录中的文件数。 If file count is greater than 10 it should write all names of these file in file named "BigList" otherwise it should write in file "ShortList".
如果文件数大于10,则应在“ BigList”文件中写入这些文件的所有名称,否则应在“ ShortList”文件中写入。 This should look like:
看起来应该像这样:
---<directory name>
<filename>
<filename>
<filename>
<filename>
....
---<directory name>
<filename>
<filename>
<filename>
<filename>
....
My script only works if subdirectories don't include subdirectories in turn. 我的脚本仅在子目录没有依次包含子目录的情况下才有效。 I am confused about this because it doesn't work as I expect.
我对此感到困惑,因为它无法按我预期的那样工作。 Here is my script
这是我的剧本
#!/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
How can I modify my script to produce the desired output? 如何修改脚本以产生所需的输出?
This bash script produces the output that you want: 此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
is used so that when a directory is empty, the loop will not run. shopt -s nullglob
,以便在目录为空时不会运行循环。 The body of the function is within ( )
so that it runs within a subshell. 函数的主体位于
( )
之内,因此它可以在子shell中运行。 This is for convenience, as it means that the function returns to the previous directory when the subshell exits. 这是为了方便起见,因为这意味着当子shell退出时,该函数返回到先前的目录。
Hopefully the rest of the script is fairly self-explanatory but if not, please let me know and I will be happy to provide additional explanation. 希望脚本的其余部分很容易解释,但如果不是这样,请告诉我,我很乐意提供其他解释。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.