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

Reading Files

In this page:

  1. Reading Files

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

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.