← Back to Bash Course | Chapter 9: File Testing & Filesystem | Lesson 3 of 13

Reading Files

Reading a file is like reading a book aloud one line at a time, so you never have to hold the whole book in your hands at once.

In this page:

  1. Reading Files
Syntax
bash
while read -r line; do
  commands using "$line"
done < file_name

cat file_name

Reading Files

You can read an entire file with cat, or process it line by line with while read -r line; do ... done < file, which is safer for large files since it doesn't load everything into memory at once.

read -r prevents backslashes from being interpreted as escape characters. Line-by-line reading is the standard approach when each line needs individual processing.

Note: Always use read -r (raw mode) unless you specifically want backslash escapes interpreted.

Example: Reading Files

bash
#!/bin/bash
printf "line one\nline two\nline three\n" > data.txt

while read -r line; do
    echo "Read: $line"
done < data.txt
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Using for line in $(cat file), which splits on spaces and not only on lines; use while IFS= read -r line.
  2. Forgetting -r in read, so backslashes are removed.
  3. Reading a file into a variable with $(cat file) and losing the trailing newlines.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.