Read File Line By Line In Bash

Linux bash is a powerful command-line interface and scripting language. It provides different features like reading file line by line from the command line. In this tutorial, we will examine different ways to read a file which is generally a text file line by line.

Read File Line By Line with read Command

The bash provides the read command which is a built-in command provided by default. The read command reads the given file for a single line every time it called. the read command can be merged with the while loop where multiple lines can be read repetitively. This can be done with a one-liner or single line bash command line below.

$ while read line; do echo $line; done < sample.txt

The output is like below where there are some epmty lines.

Read File Line By Line with read Command

Read File Line By Line with Bash Script File

We can also create a bash script file which can be called from the bash environment in order to read the specified file line by line. We will use the $filename variable in order to store the file path and name. We will use “” as the script file name.



while read line; do 
   echo $line; 
done < $filename

After creating the script file the script file can be called like below where we should provide the bash command and the script file name.

$ bash 

The output will be like below.




But to make things more readable we will make this script file directly executable with the chmod u+x command like below.

$ chmod u+x

After that we can executed the script file named .

$ ./

Also we can specify the bash script file with its full path or absolute path like below.

$ /home/ismail/
See also  Linux Bash Reading File Tutorial

Leave a Comment