Shell Scripting / Bash Tricks
Stop wrestling with nested loops in your scripts
🧩 The Challenge
Dealing with a pile of CSV files and trying to parse them line by line usually ends up with a messy, slow script full of nested loops. I spent half a Saturday trying to debug a bracket mismatch in a script that was just too damn complex for what it was doing.
💡 The Fix
Use the mapfile command to read those lines directly into an array. It is way cleaner than a while read loop and keeps your memory usage from exploding.
mapfile -t my_array < data.csv
for line in "${my_array[@]}"; do
IFS=',' read -r col1 col2 col3 <<< "$line"
echo "Processing $col1 and $col2"
done
⚙️ Why It Works
By loading the entire file into an array at once, you avoid the subshell overhead that kills performance in those old-school loops. It handles whitespace and weird line endings way better than typical piping, too.
🚀 Pro-Tip: Use mapfile -n 100 if you only need the first few lines for a quick check.
Linux Tips & Tricks | © ngelinux.com | 10/23/2026
