Authors Top

If you have a few years of experience in the Linux ecosystem, and you’re interested in sharing that experience with the community, have a look at our Contribution Guidelines.

1. Overview

In this tutorial, we’ll create a small script that reads a text file line by line.

This script can be helpful when we want to do a specific operation on each line of a text file. For instance, we can print each line on the screen.

2. The Text File

Let’s assume we have a text file named lines.txt:

$ cat lines.txt 
first	line
second	line
\\third	line

Now that we’ve created our text file, let’s take a look at the script.

3. The Script

The script should receive the file name as an argument. To clarify, the $1 variable holds the first argument:

#!/bin/bash

# Receive file name as first argument
file_name=$1

while read -r line; do
    # Reading line by line
    echo "$line"
done < $file_name

Here, we just print the line variable on the screen. In addition, if we want to do something else, we can just replace the echo “$line” line. Moreover, the -r flag tells read not to allow backslash escapes.

As a result, the third line will be displayed exactly the way it is.

4. Making the Script Executable

Now that we’ve created the script, we should make it executable:

$ chmod u+x read_lines.bash

The script is now executable.

5. Running the Script

We need to give the file name to the script as an argument:

$ ./read_lines.bash lines.txt 
first	line
second	line
\\third	line

We can see that each line is successfully displayed on the screen.

6. Conclusion

In short, we learned how to create a Bash script that reads a text file line by line and displays each line on the screen.

Authors Bottom

If you have a few years of experience in the Linux ecosystem, and you’re interested in sharing that experience with the community, have a look at our Contribution Guidelines.

Comments are closed on this article!