Linux 为什么这个变量没有被改变?

Linux 为什么这个变量没有被改变?,linux,bash,Linux,Bash,我有一个较大的脚本,但这个较小的脚本显示了问题: #!/bin/bash x=0 if [[ $x == 0 ]] then ls | while read L do x=5 echo "this is a file $L and this is now set to five --> $x" done fi echo "this should NOT be 0 --> $x" 如果该变量设置在while循环之外,那么它将按照我的预期工作。

我有一个较大的脚本,但这个较小的脚本显示了问题:

#!/bin/bash
x=0
if [[ $x == 0 ]]
then
   ls | while read L
   do
     x=5
     echo "this is a file $L and this is now set to five --> $x"
   done
fi
echo "this should NOT be 0 --> $x" 
如果该变量设置在while循环之外,那么它将按照我的预期工作。
bash版本是3.2.25(1)版本(x86_64-redhat-linux-gnu)。如果这是很明显的事情,我会觉得很傻。

设置为5的
x
在子shell中(因为它是管道的一部分),子shell中发生的事情不会影响父shell

通过在
bash
中使用进程替换,可以避免使用子shell并获得预期的结果:

#!/bin/bash
x=0
if [[ $x == 0 ]]
then
   while read L
   do
     x=5
     echo "this is a file $L and this is now set to five --> $x"
   done < <(ls)
fi
echo "this should NOT be 0 --> $x"

这是一个常见的问题。阅读常见问题解答:另一个很棒的链接:检查类似的线程:。哎哟!真尴尬。感谢亚历克斯·丹尼尔·雅基门科和乔纳森·莱弗勒。
#!/bin/bash
x=0
if [[ $x == 0 ]]
then
   ls | 
   {
   while read L
   do
     x=5
     echo "this is a file $L and this is now set to five --> $x"
   done
   echo "this should NOT be 0 --> $x"
   }
fi
echo "this should be 0 still, though --> $x"