Bash - Read every line of a file

By xngo on June 17, 2019

counter=0
while IFS='' read -r line || [[ -n "${line}" ]]; do
    echo "Do something ${line}"
    let counter+=1
done < <( cat somefile.txt )
echo "Total lines = ${counter}"
  • cat somefile.txt: Send all content of file to while loop.
  • read -r line: Use read command to read line and put value in line variable.
  • IFS='': Redefine internal field separator(IFS) equal to empty string. This will enable us to read line with spaces too.

Example of output

Do something some line A
Do something some line B
Do something some line C
Total lines = 3

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.