How to Read a File Line by Line in Bash Script
In Bash, you can read a file line by line using a
while loop combined with the read command like this: while IFS= read -r line; do ... done < filename. This reads each line safely, preserving spaces and special characters.Syntax
The basic syntax to read a file line by line in Bash uses a while loop with the read command. Here is the pattern:
while: starts the loop that runs until all lines are read.IFS=: sets the Internal Field Separator to empty to preserve leading/trailing spaces.read -r line: reads one line into the variableline,-rprevents backslash escapes.do ... done < filename: executes commands for each line, reading from the file.
bash
while IFS= read -r line; do # process each $line here echo "$line" done < filename
Example
This example reads a file named example.txt line by line and prints each line with a prefix.
bash
while IFS= read -r line; do echo "Line read: $line" done < example.txt
Output
Line read: Hello, world!
Line read: This is a test.
Line read: Bash scripting is fun!
Common Pitfalls
Common mistakes when reading files line by line in Bash include:
- Not setting
IFS=, which can trim leading/trailing spaces. - Omitting
-rinread, causing backslashes to be interpreted. - Using a pipe to feed the file, which runs the loop in a subshell and can cause variable scope issues.
Correct approach uses input redirection < filename instead of a pipe.
bash
wrong way: cat filename | while read line; do echo "$line" done right way: while IFS= read -r line; do echo "$line" done < filename
Quick Reference
| Command | Description |
|---|---|
| while IFS= read -r line; do ... done < filename | Read file line by line safely |
| IFS= | Preserves spaces in lines |
| read -r | Reads line without interpreting backslashes |
| done < filename | Redirects file input to the loop |
| Avoid: cat file | while read ... | Runs loop in subshell, variable scope issues |
Key Takeaways
Use 'while IFS= read -r line; do ... done < filename' to read lines safely.
Set IFS= to keep leading and trailing spaces intact.
Use the '-r' option with read to prevent backslash escapes.
Avoid piping file content into while loops to prevent subshell issues.
Input redirection '< filename' is the preferred way to feed the file.