Loops & Reading Files

for over words, ranges and files, while read for line-by-line processing, break and continue.

Loops in Bash usually go over one of three things: a list of words, a range of numbers, or the lines of a file. The last one has a specific safe idiom worth memorizing: while IFS= read -r line.

Looping

for board in rev_a rev_b rev_c loops over words.

for (( i = 1; i <= 3; i++ )) is the C-style form; {1..5} expands to 1 2 3 4 5.

while IFS=, read -r test board status duration splits each CSV line at commas into four variables; -r keeps backslashes literal.

for f in *.log loops over matching file names safely, even with spaces in them.

continue skips to the next iteration, break leaves the loop.

Notes

for f in $(ls *.log); do for f in *.log; do Parsing ls output breaks on file names with spaces or special characters; a glob gives each file name as one item.

Why does a counter incremented inside cat file | while read ... print 0 afterwards?

The pipeline runs the while loop in a subshell; its variables disappear when the subshell ends. Use while ... done < file instead.