ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)
Set your Publisher ID in src/config/ads.ts to display live ads.
Bash Shell Scripting Tutorial• 7 min read
Loops & Reading Files Line-by-Line
for loops, while loops, and the robust while IFS= read -r line idiom
Bash iterates over lists of words, numeric ranges, and file contents. Reading files line-by-line requires the robust while IFS= read -r line pattern.
The Canonical File Reading Loop
for item in "${array[@]}"; do ... done.
for i in {1..5}; do ... done.
CRITICAL IDIOM: while IFS= read -r line; do ... done < file.txt.
IFS= prevents stripping leading/trailing whitespace.
-r prevents backslash character escapes from being mangled.
Reading Configuration Line-by-Line
#!/usr/bin/env bash
# Reading a file safely line-by-line
while IFS= read -r line || [[ -n "$line" ]]; do
# Skip empty lines and comment lines
if [[ -z "$line" || "$line" =~ ^# ]]; then
continue
fi
echo "Processing record: $line"
done < "servers.txt"ADVERTISEMENT
Google AdSense Slot (inContentBanner)
Set your Publisher ID in src/config/ads.ts to display live ads.
Test Yourself With Exercise
Why should you always include `-r` when reading a file with `read -r line` in Bash?