How to Read a File in Bash: Simple Commands and Examples
In bash, you can read a file line by line using a
while loop combined with read. Alternatively, use cat filename to display the whole file content at once.Syntax
Here is the basic syntax to read a file line by line in bash:
while read line; do- starts a loop reading each line into the variablelinecommands- commands to process each linedone < filename- ends the loop and redirects the file as input
bash
while read line; do echo "$line" done < filename.txt
Example
This example reads a file named example.txt line by line and prints each line with a prefix.
bash
while read line; do echo "Line: $line" done < example.txt
Output
Line: Hello
Line: This is a file
Line: Read line by line
Common Pitfalls
Common mistakes when reading files in bash include:
- Not redirecting the file into the
whileloop, causing it to wait for keyboard input. - Using
readwithout quotes, which can cause word splitting and lose spaces. - Trying to read a file with spaces or special characters without proper quoting.
bash
Wrong way: while read line; do echo $line done # This waits for keyboard input instead of reading a file Right way: while read line; do echo "$line" done < filename.txt
Quick Reference
| Command | Description |
|---|---|
| while read line; do ... done < file | Read file line by line safely |
| cat file | Print entire file content |
| read -r line | Read line without interpreting backslashes |
| echo "$line" | Print line preserving spaces |
Key Takeaways
Use a while loop with read and file redirection to read files line by line.
Always quote variables like "$line" to preserve spaces and special characters.
Redirect the file into the loop using
done < filename to avoid waiting for keyboard input.Use
cat filename for quick full file display but prefer loops for processing lines.Use
read -r to prevent backslash escapes from being interpreted.