在 Bash 中迭代文件并获取索引和计数

bma*_*man 8 shell-script

在 Bash 中迭代目录中的文件的正确方法是使用“for 循环”和 glob,如下所示:

for f in *.jpg; do
    echo "- Processing file: $f"
done
Run Code Online (Sandbox Code Playgroud)

但是如何检索文件的总数和循环交互的当前索引?我需要总计数,而不是累计计数来显示进度。

Spa*_*awk 9

我会将文件列表存储在一个数组中,这样您就不必两次读取文件系统,从而提高性能并减少潜在的竞争条件。然后使用另一个变量作为索引。

files=(*.jpg)
total=${#files[@]}
i=0
for f in "${files[@]}"; do
    i=$(( i + 1 ))
    echo index $i
    echo total $total
    echo "- Processing file: $f"
done
Run Code Online (Sandbox Code Playgroud)

解释

  • files=(*.jpg): 将 glob 存储到数组中 $files
  • total=${#files[@]}: 将总数读入 $total
  • i=0: 初始化$i为 0。
  • i=$(( i + 1 )):$i每个循环加 1

这假定“第一个”循环为 1。根据您的意见,您可能希望从 0 开始。