0
0
Bash-scriptingHow-ToBeginner · 3 min read

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 variable line
  • commands - commands to process each line
  • done < 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 while loop, causing it to wait for keyboard input.
  • Using read without 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

CommandDescription
while read line; do ... done < fileRead file line by line safely
cat filePrint entire file content
read -r lineRead 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.