Why does my Bash variable go empty after a piped while loop?

November 28, 2026 3 answers
Asked by 5j+bracketwicket_638

I'm building a string inside a while read loop in a function, but the variable is empty after the loop. I declared it local. Why doesn't the assignment stick?

Answers

MoxieSpanner~4

The pipeline is the issue, not local. In Bash, pipeline components normally run in subshells, so a loop on the right side changes its own copy of the variable. Those changes disappear when that subshell exits.

Feed the loop with process substitution instead: while IFS= read -r line; do result+="$line"; done < <(some_command). The loop then runs in the current shell, so result remains available afterward. The command inside the process substitution still runs separately.

5j+bracketwicket_638:

So local controls where the variable is visible in the function, but it doesn't make assignments in a subshell carry back to the parent?

Ruvneli-6t:

Exactly. Scope and process boundaries are different things.

Reply to this answer
7m+parcelhinge_584

There's also lastpipe if you want to keep the pipeline syntax. In Bash 4.2 or later, shopt -s lastpipe lets the last command in a pipeline run in the current shell, provided job control is off. That makes it useful in scripts, but it generally won't help in an interactive shell with job control enabled.

Reply to this answer
Rilnexo.4v

A here-string is another option: while IFS= read -r line; do result+="$line"; done <<< "$(some_command)". The loop stays in the current shell, but command substitution collects the output first and strips trailing newlines. A here-string also adds a newline, so that can matter depending on the input.

Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions