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
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
$ while read LINE; do echo "$LINE" | cut -f1 -d":"; done < /etc/passwd root daemon bin [...]The
LINEin 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
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 Eric Kyle Stan Kenny
$ 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 LineLets 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
readfile.shfile with the
Make it executable with
chmod +x readfile.sh.
readfile.sh with a text editor and put the following code:
#!/bin/bash FILE=$1 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:
$ ./script.sh /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 [...]