Linux bash is a powerful command-line interface and scripting language. It provides different features like reading files 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 is 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 empty lines.
This read command can be also implemented in a more readable way as a bash script.
#!/bin/bash
filename="/home/ismail/names.txt"
while IFS= read -r line
do
echo "$line"
done < "$filename"
Read File Line By Line with Bash Script
We can also create a bash script file that 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 “read_line_by_line.sh” as the script file name.
#!/bin/bash
filename="/home/ismail/names.txt"
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 read_line_by_line.sh script file name.
$ bash read_line_by_line.sh
The output will be like below.
ismail ahmet ali elif ecrin
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 read_line_by_line.sh
After that, we can execute the script file named read_line_by_line.sh .
$ ./read_line_by_line.sh
Also, we can specify the bash script file with its full path or absolute path like below.
$ /home/ismail/read_line_by_line.sh