Bash & Shell Scripting (50 Qs)•Part 3: Advanced Text Processing & Production Internals (Senior / Lead)
What causes the Subshell Variable Loss trap in `while` loops with pipes?
senior LevelCode ExamplePipes
In Simple Words: The classic Bash pitfall:
bash
count=0
cat numbers.txt | while read -r num; do
count=$((count + num))
done
echo "Total: $count" # Prints 0! Why?
- In Bash, the right side of a pipeline (
|) runs in a child subshell! - The
$countvariable inside the loop is incremented inside the child process and destroyed when the loop ends. - Fix: Use process redirection or input redirection directly into the loop:
bash
count=0
while read -r num; do
count=$((count + num))
done < numbers.txt
echo "Total: $count" # Correctly prints total!