Stop watching your variables turn into spaghetti in complex loops
Shell Scripting / Bash Tricks
Stop watching your variables turn into spaghetti in complex loops
🧩 The Challenge
You ever write a script that processes a file line by line, but the variables inside your loop don’t exist once the loop finishes? It’s enough to make you toss your keyboard out the window when the pipe subshell nukes your data.
💡 The Fix
Use a process substitution block instead of piping directly into your while loop. This keeps everything in the current shell context so your variables don’t just vanish into the void.
while read -r line; do
((count++))
last_line="$line"
done < <(grep "pattern" /var/log/syslog)
echo "Processed $count lines. Last one was: $last_line"
⚙️ Why It Works
Running the while loop with < <(command) prevents bash from spawning a subshell for the loop body, which is what happens when you use a pipe. Since you aren’t in a subshell, those variable assignments actually stick around after the loop wraps up.
🚀 Pro-Tip: Stick with read -r unless you enjoy debugging backslash character escapes for hours.
Linux Tips & Tricks | © ngelinux.com | 11/17/2026
