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