Fundamentals 4 min read

Four Simple Ways to Read a File Line‑by‑Line in Shell Scripts

This guide demonstrates four practical techniques—input redirection, cat with a pipe, passing the filename as a parameter, and using awk—to read a text file line by line in a Bash script, complete with code snippets and expected output.

Liangxu Linux
Liangxu Linux
Liangxu Linux
Four Simple Ways to Read a File Line‑by‑Line in Shell Scripts

Method 1: Input Redirection

The simplest approach is to use a while read loop with input redirection. Create a file mycontent.txt containing sample lines, then write example1.sh:

#!/bin/bash
while read rows
do
  echo "Line contents are : $rows "
done < mycontent.txt

Running the script prints each line prefixed with the custom message.

Method 2: cat and Pipe

Use cat to output the file and pipe it into the while loop:

#!/bin/bash
cat mycontent.txt | while read rows
do
  echo "Line contents are : $rows "
done

The pipe feeds each line to the loop, achieving the same result.

Method 3: Filename as a Parameter

Pass the file name to the script via $1 and redirect input from that argument:

#!/bin/bash
while read rows
do
  echo "Line contents are : $rows "
done < $1

Invoke the script with ./example3.sh mycontent.txt to process any file.

Method 4: Using awk

One‑liner with awk can print each line with a prefix:

cat mycontent.txt | awk '{print "Line contents are: "$0}'

This command directly streams the file through awk without an explicit loop.

Conclusion

The article shows how to read a file line by line in Bash using four different methods, each useful in various scripting scenarios such as searching for strings or processing logs.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

ShellBashwhile-loopawkFile Reading
Liangxu Linux
Written by

Liangxu Linux

Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.