Re:Shell programming with bash: by example, by counter-example
by unhammer on Friday January 17, 2014 @03:01AM
(#7074792)
They work 100 % of the time if you do it right. An example:
find . -type f -name foo -print0 | while read -rd ''; do
grep -l bar "${REPLY}"
done
find separates its output with the NUL byte when you do -print0, and -d '' means read NUL-separated input.Of course, in this case it would be better to use:
find . -type f -name foo -print0 | xargs -0 -I{} grep -l bar '{}'
but if you've got several things to do for each file, the first one makes sense (or you can put those several things in a script, and use xargs).
Things like 'while read -r line; do {stuff with $line}; done'
These idioms have issues for their most common uses (e.g. dealing with filenames with embedded newlines), but they do work 99% of the time.