Skip to main content
InterviewHubPRO
Section Overview
Q25

Question 25 of 50

Part 3: Advanced Text Processing & Production Internals (Senior / Lead)

50%
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 $count variable 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!