英文:
why bash read command create a loop-local variable?
问题
我编写了以下的bash脚本。read命令创建了变量`var`。
如果`$var==5`,则退出循环。
```bash
seq 10 | while read -r var
do
echo "read: $var"
if [[ $var == 5 ]]; then
echo "break loop: $var"
break
fi
done
echo "after loop: $var"
这是输出结果
read: 1
read: 2
read: 3
read: 4
read: 5
break loop: 5
after loop:
问题是:为什么循环结束后,$var
变成空的?
<details>
<summary>英文:</summary>
I wrote following bash script. The read command creates variable `var`.
if `$var==5` then break loop.
```bash
seq 10 | while read -r var
do
echo "read: $var"
if [[ $var == 5 ]]; then
echo "break loop: $var"
break
fi
done
echo "after loop: $var"
Here is the output
read: 1
read: 2
read: 3
read: 4
read: 5
break loop: 5
after loop:
My question is: why after loop, $var
is empty?
答案1
得分: 2
变量不是循环局部的,与read
和循环相关的部分都是干扰项。你看到的行为是因为管道启动了一个子shell。如果你去掉管道,运行这段代码代替:
while read -r var
do
echo "read: $var"
if [[ $var == 5 ]]; then
echo "break loop: $var"
break
fi
done < <(seq 10)
echo "after loop: $var"
那么输出将会是:
read: 1
read: 2
read: 3
read: 4
read: 5
break loop: 5
after loop: 5
英文:
The variable isn't loop-local, and everything related to read
and loops here are just red herrings. The behavior you're seeing is because the pipe starts a subshell. If you get rid of the pipe and run this code instead:
while read -r var
do
echo "read: $var"
if [[ $var == 5 ]]; then
echo "break loop: $var"
break
fi
done < <(seq 10)
echo "after loop: $var"
Then it will print this instead:
read: 1
read: 2
read: 3
read: 4
read: 5
break loop: 5
after loop: 5
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论