Misuse of for loops

In code samples on the internet and others' shell scripts, you will often find command substitution used with for to iterate over lines of output; this is especially common with commands such as ls, cat, and grep:

# Bad practice
for item in $(ls) ; do
    ...
done
for line in $(cat TODO.txt) ; do
    ...
done
for match in `grep username ~/accounts` ; do
    ...
done

You should never attempt to iterate over lines with for loops, as in the preceding examples. The primary reason for this is that other characters besides newlines can separate arguments  spaces, for example. Another is that in order for the preceding code to work, the command substitution has to be unquoted, meaning that characters such as * or ? in the output can wreak ...

Get Bash Quick Start Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.