Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Looping through the content of a file in Bash
Reading file contents line by line is a common requirement in Bash scripting. There are several approaches to accomplish this task, each with its own advantages depending on your specific needs.
Creating a Sample File
First, let's create a sample file to work with ?
# Create the file cat > a_file.txt << EOF Monday Tuesday Wednesday Thursday Friday Saturday Sunday EOF # Display the file contents cat a_file.txt
Monday Tuesday Wednesday Thursday Friday Saturday Sunday
Using While Loop with Read
The most common and reliable method uses a while loop with the read command ?
#!/bin/bash
while read line
do
echo "$line"
done < a_file.txt
Monday Tuesday Wednesday Thursday Friday Saturday Sunday
Using For Loop with Command Substitution
This approach uses a for loop with command substitution to iterate through each line ?
#!/bin/bash
file="a_file.txt"
for line in $(cat $file)
do
echo "$line"
done
Monday Tuesday Wednesday Thursday Friday Saturday Sunday
Using Echo with Command Substitution
You can display all file contents at once using echo, but this will output everything on a single line ?
echo $(< a_file.txt)
Monday Tuesday Wednesday Thursday Friday Saturday Sunday
Handling Files with Blank Lines
When your file contains blank lines, you can preserve or skip them using the Internal Field Separator (IFS) ?
#!/bin/bash
while IFS= read -r line
do
echo "$line"
done < a_file.txt
Monday Tuesday Wednesday Thursday Friday Saturday Sunday
Comparison of Methods
| Method | Handles Spaces | Preserves Blank Lines | Best For |
|---|---|---|---|
| While + Read | Yes | With IFS= | Most reliable |
| For Loop | No | No | Simple word processing |
| Echo | No | No | Quick display |
Conclusion
The while read method is the most robust approach for reading files line by line in Bash. Use IFS= read -r to preserve whitespace and handle special characters properly.
