Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

i=$((step));
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, …"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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:

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading