[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Scope change in loops with "read" built-in
From: |
Linde, Evan |
Subject: |
Scope change in loops with "read" built-in |
Date: |
Tue, 2 Apr 2024 20:08:57 +0000 |
In a loop constructed like `... | while read ...`, changes to
variables declared outside the loop only have a loop local
scope, unlike other "while" or "for" loops.
So far, I have found this in every bash version I have tested
(as low as 3.2.57 on an old mac and as high as 5.2.15).
Nothing obvious in the manual seems to point to this. Specifically
I've checked the section for the "read" builtin and everywhere
I can find the word "scope". Additionally, for comparison, this
doesn't seem to be replicated in zsh.
I would expect all of these to produce "blah1 blah2 1 2 3 4" as
the final output from `echo ${a[@]}`, but the output from the
first is only "blah1 blah2".
# Unexpected final output
a=("blah1" "blah2")
printf "%s\n" {1..4} | while read n; do
a+=(${n})
echo ${a[@]}
done
echo "finished loop"
echo ${a[@]}
# Final output as expected
a=("blah1" "blah2")
n=1
while [[ $n -le 4 ]]; do
a+=(${n})
echo ${a[@]}
n=$(( $n + 1 ))
done
echo "finished loop"
echo ${a[@]}
# Final output as expected
a=("blah1" "blah2")
for ((n=1;n<=4;n++)); do
a+=(${n})
echo ${a[@]}
done
echo "finished loop"
echo ${a[@]}
Evan Linde
Research Cyberinfrastructure Analyst
Oklahoma State University
High Performance Computing Center
405-744-1455
http://hpcc.okstate.edu/
- Scope change in loops with "read" built-in,
Linde, Evan <=