Bash: Read File Line By Line – While Read Line Loop

The while loop is the best way to read a file line by line in Linux.

If you need to read a file line by line and perform some action with each line – then you should use a while read line construction in Bash, as this is the most proper way to do the necessary.

In this article i will show the general syntax of the while read line construction in Bash and an example of how to read a file line by line from the Linux command line.

I will also show an example of the Bash script that reads an input file line by line and prints each line with some appended text.

Cool Tip: Make your Bash script interactive! Teach it to prompt for “Yes/No” confirmation. Read more →

While Read Line Loop in Bash

The general while read line construction that can be used in Bash scripts:

while read LINE
    do COMMAND
done < FILE

The same construction in one line (easy to use on the Linux command line):

while read LINE; do COMMAND; done < FILE

As example lets print all users from the /etc/passwd file:

$ while read LINE; do echo "$LINE" | cut -f1 -d":"; done < /etc/passwd

The LINE in this construction – is the name of a variable that stores the line during each loop iteration.

You can change it to the more appropriate name, depending on the contents of a FILE.

For example, if you store a list of users in a FILE – it would be better to name this variable not the LINE but the USER, as follows:

$ cat users.txt
$ while read USER; do echo "Hello $USER!"; done < users.txt
Hello Eric!
Hello Kyle!
Hello Stan!
Hello Kenny!

Cool Tip: Write a command once and have it executed N times using Bash FOR loop! Read more →

Bash Script: Read File Line By Line

Lets create a Bash script, that takes a path to a file as an argument and prints "This is a line:" before the each line of this file.
Create an empty file with the touch command.

Make it executable with chmod +x

Open the with a text editor and put the following code:

while read LINE; do
     echo "This is a line: $LINE"
done < $FILE

Cool Tip: Do not be a bore! Add COLORS to your Bash script! Make it look AWESOME! Read more →

Save and execute the script:

$ ./ /etc/passwd
This is a line: root:x:0:0:root:/root:/bin/bash
This is a line: bin:x:1:1:bin:/bin:/sbin/nologin
This is a line: daemon:x:2:2:daemon:/sbin:/sbin/nologin

2 Replies to “Bash: Read File Line By Line – While Read Line Loop”

  1. А как бы читать кусками по N строк?

  2. I knew there was a way to do it without programming it. Actually programming it would make it look cleaner. It is easy to do and the system calls are inside the executable.

Leave a Reply