For loop statements order of operations

Say I have a for loop that parse through a file....Say it look for the colors red and blue in sections of the file. Say it find red before it find blue in the file.

Say I have two if statements in the for loop

Something like if blue is found print blue is my favorite color is the first if statement.

A second if statement if red is found print red is my favorite color.

Considering my if statements are in the opposite order of the colors found in the file which if statement get printed first and why?

You're reading the file in sequential order. The order of your if statements is unimportant for the requirement you specified.

Why is that? I thought code was read from top to bottom. So why doesn't hitting the first if statement first doesn't matter?

So basically what you are saying is all the code in the for loop code block is essentially executed at the same time?

I don't think that's what I said at all. If you are reading the file sequentially, you'll always get whatever color comes first, regardless of the order in which you process it.

Or maybe I'm not grasping your question. It seems straight forward, but it is late, and I maybe need some sleep!

$ cat file
red
green
blue
for color in line; do
  [ "$color" = red ] && echo "I found red"
  [ "$color" = blue ] && echo "I found blue"
done < file
I found red
I found blue
for color in line; do
  [ "$color" = blue ] && echo "I found blue"
  [ "$color" = red ] && echo "I found red"
done < file
I found red
I found blue

Scott,

Is the reason this work this way is because the for loop is processing one color at a time before moving to the next color?

Yes. It works this way because you are reading a file (sequentially) and processing it as it comes.

if you find red, process that
if you find blue, process that

Yields the same results as

if you find blue, process that
if you find red, process that

if you're processing the same file.

If you were to read the entire file first, and store it somewhere, then the order of the processing would matter.

e.g.

for color in line; do
  [ "$color" = red ] && foundred=y
  [ "$color" = blue ] && foundblue=y
done < file

[ "$foundred" = y ] && echo found red
[ "$foundblue" = y ] && echo found blue
found red
found blue

Would be different with...

for color in line; do
  [ "$color" = red ] && foundred=y
  [ "$color" = blue ] && foundblue=y
done < file

[ "$foundblue" = y ] && echo found blue
[ "$foundred" = y ] && echo found red

found blue
found red
1 Like

I think what is meant in this thread is to use a while read loop rather than a for loop:

while read color
do
  ....
done < file

Yes, a for loop processes a word list, not good for proccessing a file line by line.
A while read loop is appropriate.
The read command processes one (more) line, so each loop cycle processes one line (until the read has bad exit status because there are no more lines).
Within a cycle the conditions are processed in sequence.