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?
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
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
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.