1

I have a for loop like the below. I want to know if it is possible to check through all previous iterations of a for loop?

Where I am on the fourth iteration and $i is 4:

for ((i=1;i<9;i++)); do                 #$i is currently 4
     while (($x == 3)) || (($x == 2)) || (($x == 1)); do 
       echo "Something"
     done 
done

But when $i is 5:

for ((i=1;i<9;i++)); do                 #So $i is now 5 
     while (($x == 4)) || (($x == 3)) || (($x == 2)) || (($x == 1)); do
       echo "Something"
     done
done

Is it possible to check all previous iterations like the above in a more simple way? I know I could check with $i-1 $i-2 but how do I code when to stop?

Bobybobp
  • 95
  • 9
  • In while loop, you are checking for a boolean value either true or false or 1 0r 0, then use if-else instead. This will make code termination when upper for loop ends ie when $i reaches 8. – Avinash Yadav Sep 13 '19 at 09:50
  • What do you actually want to do with it? You can obviously get the value of i by echoing it in the for loop. – Lorccan Sep 13 '19 at 09:50
  • I will need it to stay as a while I believe as I will need to perform the action until the while loop returns false at which point it can stop. I'm checking numbers in multiple arrays to see if they match, if they do match they keep swapping them until they don't match. e.g. I could swap one of my values and complete the if else statement but still might need to swap the value again, hence the need for a while loop I think? – Bobybobp Sep 13 '19 at 09:53
  • I guess I could use an if else statement or a switch case and then a while loop within that, but to me that seems messy. But I'm not so sure if that's the only way. It also wouldn't work if I ever needed to expand my arrays as the values to search would be hard coded. – Bobybobp Sep 13 '19 at 10:04
  • 1
    If you are just comparing arrays, you don't need to do any iteration to determine if they match. (Have a look here: https://stackoverflow.com/questions/2312762/compare-difference-of-two-arrays-in-bash particularly at the comments in the answer with 102 votes) If that's not what you're doing, you'll need to explain more clearly what you want. – Lorccan Sep 13 '19 at 10:15
  • I'm not looking to compare whole arrays or individual elements of arrays, I need to compare an element of one array to every previously checked array, which is why I'm more interested in how the while loop could work. Comparing the actual elements isn't the problem, the problem is comparing my current array to **all** of the previous ones. – Bobybobp Sep 16 '19 at 08:24

0 Answers0