1

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

#!/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)。如果这是显而易见的事情,我会感到很愚蠢。

4

1 回答 1

3

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

您可以避免使用子外壳程序并通过在以下中使用进程替换来获得预期的结果bash

#!/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"
于 2013-08-28T14:54:40.850 回答