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"
Create a free account and build your private vault. Share publicly whenever you want.