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.
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.txtRunning 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 "
doneThe 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 < $1Invoke 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.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.)
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
