It is often necessary to read a file with bash, and act upon the entire line. There are many different ways to do this, but I’ll outline one of the simpler methods, both suitable for stacking on a single command line.
For this exercise I’ll assume the file is a list of files that we need to execute a command on.
# cat file.lst |while read line; do echo "${line}"; done
/tmp/file1.txt
/tmp/file with space.txt
#
All we’ve managed to do here is cat the file. Alternately we could move the cat to the end of the while loop as follows:
# while read line; do echo "${line}"; done < <(cat file.lst)
/tmp/file1.txt
/tmp/file with space.txt
#
The beauty of this solution lies in the handling of whites paces in a filename, a simple for loop would have broken the filenames in separate tokens.
Leave a Reply