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:
Syntax
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
#!/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 try C/C++/Java/PHP code in the editor
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
- Using
for line in $(cat file), which splits on spaces and not only on lines; usewhile IFS= read -r line. - Forgetting
-rinread, so backslashes are removed. - Reading a file into a variable with
$(cat file)and losing the trailing newlines.
🔒
Chapter Quiz — Complete all 13 topics to unlock
0/13 topics done
Complete these topics first: