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

时间:2013-08-28 14:39:59

标签: 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循环之外,那么它就像我期望的那样工作。 bash版本是3.2.25(1)-release(x86_64-redhat-linux-gnu)。如果这是显而易见的事情,我会感到很愚蠢。

1 个答案:

答案 0 :(得分:3)

设置为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"

现在while循环是主shell进程的一部分(只有ls在子进程中),因此变量x会受到影响。

我们可以讨论另一次解析ls输出的优点;这个问题在很大程度上是偶然的。

另一种选择是:

#!/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"