我有一个更大的脚本,但是这个较小的脚本显示了问题:
#!/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)。如果这是显而易见的事情,我会感到很愚蠢。
答案 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"