Bash

Read File Line-By-Line (the safe way)

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
The classic `for line in $(cat file)` is wrong — it word-splits and globbing fires on filenames. Use `while IFS= read -r line` with input redirection.
Bash
Raw
while IFS= read -r line; do
    echo "got: $line"
done < /etc/hosts

# Read AND track line numbers
n=0
while IFS= read -r line; do
    ((n++))
    printf '%4d  %s\n' "$n" "$line"
done < /etc/hosts

# Process stdin instead of a file
some_command | while IFS= read -r line; do
    echo "stdin: $line"
done
# WARNING: piping into `while` runs the loop in a subshell —
# variable changes won't survive. Use process substitution:
while IFS= read -r line; do
    count=$((${count:-0} + 1))
done < <(some_command)
echo "total: $count"
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.