Reading a file line by line in Bash

Posted: 26th July 2015 by Tim in Bash, Linux
Tags: , , , , , , ,

There are a few ways to read a file in bash, each with their own caveats. If you’re looking to read a file line-by-line verbatim, including blank lines, then using a simple while loop should do the trick. For example, the following code will print the contents of a file with line numbers:


line_no=0
while IFS='' read -r line
do

    ((++line_no))
    echo "$line_no: $line"
done < /etc/kderc

This will print something like:

1: [Directories]
2: kioskAdmin=root:
3: profileDirsPrefix=/usr/share/kde-settings/kde-profile/
4: userProfileMapFile=/etc/kde-user-profile
5:
6: [Directories-default]
7: prefixes=/usr/share/kde-settings/kde-profile/default/