bash shell脚本中的全局变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7885732/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 00:59:46  来源:igfitidea点击:

Global Variable in shell script

bashshell

提问by Vivek Goel

I would like to make za global variable in the following code:

我想z在以下代码中创建一个全局变量:

#!/bin/bash                                                                                                                          
z=0;
find  -name "*.txt" | \
while read file
do
  i=1;
  z=`expr $i + $z`;
  echo "$z";
done
echo "$z";

The last statement always outputs "0". Why?

最后一条语句总是输出“0”。为什么?

回答by glenn Hymanman

The simple way to translate

简单的翻译方法

find ...  | while read ...; done

to a form without pipes is using process substitution:

到没有管道的表单正在使用进程替换

while read ...; done < <(find ...)

Readability suffers somewhat.

可读性受到一些影响。

回答by lya

I don't know why this happened, but the problem is caused by the pipe.

我不知道为什么会发生这种情况,但问题是由管道引起的。

If you do it like this

如果你这样做

#!/bin/bash                                                                                                                          
    z=0;
    for f in `find  -name "*.txt"`
    do
    i=1;
    z=`expr $i + $z`;
    echo "$z";
    done
    echo "$z";

then $z will not be zero.

那么 $z 不会为零。