bash:for 循环不会递增 1。我怎样才能像对待它一样处理它以获得每个循环的索引(1、2、3 等)?

bash: a for loop does not increment by 1. How can I treat it like it does in order to get the index (1, 2, 3, etc) of each loop?

我有这个循环,只允许我处理模拟中的特定时间步长:

    let ALLSTEPS=820000
    for ((step=20000; step <= ALLSTEPS; step+=20000)); do
        echo "Step: $step"
...

在循环中,我需要从外部文件的每一行中读取一行。这是我的:

i=$((step));
k=$(sed "${i}q;d" externalFile.txt)
echo ${k%}

这不起作用,因为在外部文件中,我的行是:1、2、3、4 等,而“步骤”是“20000、40000、60000,...”

我可以设置另一个循环,但这似乎很笨拙,我想知道是否有更简洁的方法来做到这一点?

每个算术循环可以使用多个变量:

ALLSTEPS=820000
for ((i=1, step=20000; step <= ALLSTEPS; i++, step+=20000)); do
    echo "Step: $step, i: $i"
done

而不是使用 sed(它将读取整个文件,只挑出一行),为什么不在循环中使用 read 每次读取下一行?

for ((step=20000; step <= ALLSTEPS; step+=20000)); do
    IFS= read -r k <&3    # Read the next line from the external file
    echo "Step: $step, k: $k"
    ...
done 3<externalFile.txt

在上面,我为文件使用了 FD #3(3<<&3 的东西),以避免在循环中读取该文件时与标准输入发生冲突。

( read 命令中的 IFS=-r 内容是告诉 read 只读原始行的标准方法,不要“有帮助” " 对其进行预处理。)