# We have already seen simple ‹for› loops, even though we didn't # quite understand variables. For loops are quite simple: for var in x y z; do echo $var done # By now, you should understand what ‹echo $var› means, and the # ‹for› loop simply means this: set ‹var› to ‹x›, run the body of # the loop, then set it to ‹y›, run the loop again and then set it # to ‹z› and repeat once more. The basic structure is like with # ‹if›: you can use semicolons or newlines, as you prefer. # Of course, the above form of a loop can be useful, but the things # to iterate will often be files. You may remember that we can use # «globs» (patterns) to match multiple files. This works # universally, not just in a for statement: echo *.mk echo for file in *.txt; do if test $file -nt make.txt; then echo "$file is newer than make.txt" else echo "$file is older than make.txt" fi done # The last form of a loop that I want to show you is a ‹while› loop. # It is written like this: echo touch scratch.txt while test $(wc -l < scratch.txt) -lt 5; do echo . >> scratch.txt done wc -l scratch.txt # We can also pipe things to and from loops: for i in 1 2 3 4 5; do echo . done | wc -l echo # Especially useful (when piping things into loops) is the ‹while # read› construct. The ‹read› command is provided by the shell to # read inputs and put them into variables. ‹command | read var› is # similar to ‹var=$(command)›. You can try running: # # $ echo bla | read foo # $ echo $foo # # The loop version looks like this: cat scratch.txt | while read line; do echo the line is this: $line done # That is all about loops. You can now go on to ‹2.txt›: # # $ cat 2.txt