bash 脚本中的变量重置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8086376/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
variable reset in a bash script
提问by sof
a simple variable test:
一个简单的变量测试:
#!/bin/bash
N=0
ls -l | while read L; do
N=$((N+1))
echo $N
done
echo "total $N"
ran it then output:
运行它然后输出:
1
2
3
total 0
i expected final N=3: "total 3", but why did the value reset to 0 after the loop?
我预计最终 N=3:“total 3”,但为什么在循环后该值重置为 0?
回答by Neil
bashruns each statement in a pipe in its own subshell. (For external commands such as lsthe subshell simply execs the command.) This effectively makes all of the variables local. You generally have to work around this by using redirection or command substitution instead of a pipe.
bash在其自己的子shell 中的管道中运行每个语句。(对于诸如lssubshell 之类的外部命令,只需execs 命令。)这有效地使所有变量成为本地变量。您通常必须通过使用重定向或命令替换而不是管道来解决此问题。
EDIT: This seems to work:
编辑:这似乎有效:
#!/bin/bash
IFS=
N=0
while read L; do
N=$((N+1))
echo $N
done <<<$(ls -l)
echo "total $N"

