我只想知道下面的代码片段是否也可以将与find命令匹配的文件数分配到total变量中?
total=0
counter=1
while IFS= read -r -d '' file; do
echo "process file $counter of $total"
done < <(find . -iname "*.txt" -type f -print0 | sort -zn)
注意:在循环上方执行find命令,然后计算总数并在循环中使用其结果,这是一种有效的方法吗?
我假设您想在while
逐个文件循环。但是,我们无法确定$total
的值直到while
循环结束,只要我们增加循环中的值即可。
或者,您可以先创建一个文件数组,然后进行迭代在知道$total
值的文件上。
您可以尝试以下操作:
mapfile -d "" -t files < <(find . -iname "*.txt" -type f -print0 | sort -zn)
total="${#files[@]}"
for file in "${files[@]}"; do
((++counter))
echo "process file $counter of $total"
# do something with $file
done
希望这会有所帮助。