How to raise and take care of shell scripts: Loops
Which types of loops are suitable to process input?
I think: none ;-) What I mean is: Prior to process a file or a large command's output using a loop, look for a tool, which is built exactly for those tasks. Some of these tools are sed, awk, grep, cut, tr and many other. Using such commands you will almost every time reach your goals more efficiently. But now I'll talk about loops:
There are two different basic variants: for and while. Both are different in the way to use them and both have their benefits and disadvantages:
The for loop:
# for loop, is able to process command's outputs (could also be `cat file`) # benefit: no pipe, no subshell # disadvantage: can't handle blanks, tabs ... for VAR in `some_command`; do ... done # another example redefining the input field separator (IFS) # benefit: can handle blanks and tabs # disadvantage: IFS probably must be stored and restored OLD_IFS="$IFS" IFS=' ' for VAR in `some_command`; do ... done IFS="$OLD_IFS"
The while loop (the remarks do also describe the until loop, using it you only define other exit conditions):
# while loop, processes everything coming from standard input STDIN # benefit: can handle every kind of input format # disadvantage: uses a pipe and therefore creates a subshell some_command | while read x [y ...]; do ... done # another example: input redirection # benefit: no pipe, no subshell # disadvantage: can only be fed from a file while read x [y ...]; do ... done <file