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?

I have this loop that allows me to deal only with certain time steps from a simulation:

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

Within the loop I need to read in a row from each line of an external file. This is what I have:

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

This does not work because in the external file, my rows go: 1, 2, 3, 4, etc whereas "step" is "20000, 40000, 60000, …"

I could set up another loop but that seems unwieldy and I wonder if there’s a cleaner way to do it?

>Solution :

You can use multiple variables per arithmetic for loop:

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

Leave a Reply