Search code examples
bashwhile-loopnested-loops

bash nested while: outer loop executed only once


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.


Solution

  • 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