r/bash • u/deployfan64 • 2d ago
help TIL that `local` in bash doesn't scope variables the way I assumed inside pipelines
I had a function that built a string in a while-read loop inside a pipeline, and a variable set with `local` inside the loop was coming up empty after the loop finished. Turns out each side of a pipeline runs in a subshell, so no amount of `local` helps — the assignments die with the subshell. I ended up using process substitution (`while read ... done < <(some_command)`) instead, which keeps the loop in the current shell. Cost me an hour of staring at a script that "worked" when I ran the pieces by hand.
18
Upvotes
7
u/roxalu 1d ago
One of the advantages of bash is its age: Many others have stepped into every trap that exist in bash - so once you know where bash pitfalls are documented you can avoid them quicker. See e.g. the urls linked to r/bash
3
u/jjangg96 1d ago
two ways out besides what you did. shopt -s lastpipe makes the last element of a pipeline run in the current shell, so the while loop keeps its variables. needs bash 4.2+ and job control off, so it works in a script but does nothing in an interactive shell.
the other is a here-string, done <<< "$(cmd)", which also keeps the loop in the current shell. it buffers all the output first though, process substitution streams it.
0
u/stianhoiland 2d ago edited 1d ago
Oh yeah, I struggled with this too. Even worse, `local` variables are also in scope of functions you call from the function declaring the local variables!