Site icon New Generation Enterprise Linux

Stop mangling your exit codes when piping into a while loop

Shell Scripting / Bash Tricks

Stop mangling your exit codes when piping into a while loop

đź§© The Challenge

Everyone thinks piping a command into a while loop is fine until you realize your variables aren’t there when the loop finishes. It’s because the pipe forks a subshell, and that data disappears the second the loop hits the final line.

đź’ˇ The Fix

Use process substitution instead of the standard pipe. It keeps the loop running in your current shell context so you can actually use the data you just processed.

while read -r line; do count=$((count+1)); done < <(grep "error" /var/log/syslog)
echo "Found $count errors"

⚙️ Why It Works

Bash opens the command in the parentheses, gives it a file descriptor, and lets the while loop read from it directly without creating a subshell. That way, any changes you make to variables stick around for the rest of your script.

🚀 Pro-Tip: Use this with read -r to make sure backslashes in your log lines don’t get eaten by the shell.

Linux Tips & Tricks | © ngelinux.com | 9/30/2026

0 0 votes
Article Rating
Exit mobile version