0

The outer loop in the following bash script is executed only once, but it should be executed four times:

#!/bin/bash 
NX="4"
NY="6"
echo "NX = $NX, NY = $NY"
IX="0"
IY="0"
while (( IX < NX ))
do
  while (( IY < NY ))
  do
    echo "IX = $IX, IY = $IY";
    IY=$(( IY+1 ))
  done;

  IX=$(( IX+1 ))
done

I have also tried declaring the loop variables as declare -i NX=0 (without quotes), but either way the output I get is

NX = 4, NY = 6
IX = 0, IY = 0
IX = 0, IY = 1
IX = 0, IY = 2
IX = 0, IY = 3
IX = 0, IY = 4
IX = 0, IY = 5

What is the reason for this and how do I fix it? Note that I prefer to leave NX="4" and NY="6" (with quotes), as these will actually be sourced from another script.

3
  • 3
    write echo "IX = $IX" after the first do and you'll see it loops perfectly! That is, it loops from 0 to 3. Give more context on what you want to do, so we can assist. Commented Jul 21, 2015 at 11:29
  • 3
    Why are you using while loops rather than for to start with? for ((ix=0; ix<nx; ix++)) would have been more readable, and have avoided this bug. Commented Jul 21, 2015 at 11:35
  • @CharlesDuffy The while comes from a skript that I edited to suit my needs. I simply didin't include the variable reset, hence the error. Of course, for works fine - but I was so confused by the large number of alternatives for the condition statement that I didn't want to dig into that. Commented Jul 21, 2015 at 11:42

1 Answer 1

4

You need to reset IY to 0 after it reaches 5. Change to:

#!/bin/bash 
NX="4"
NY="6"
echo "NX = $NX, NY = $NY"
IX="0"
IY="0"
while (( IX < NX ))
do
  while (( IY < NY ))
  do
    echo "IX = $IX, IY = $IY";
    IY=$(( IY+1 ))
  done;
  IY="0"
  IX=$(( IX+1 ))
done
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.