我有这样的代码
var="before"
echo "$someString" | sed '$someRegex' | while read line
do
if [ $condition ]; then
var="after"
echo "$var" #first echo
fi
done
echo "$var" #second echo
这里第一个回显打印“之后”,第二个是“之前”。如何在“之后”进行第二次回显打印。我认为这是因为管道购买我不知道怎么弄清楚。
感谢任何解决方案...
答案编辑:
我改正了它,它工作正常。感谢尤金的有用回答
var="before"
while read line
do
if [ $condition ]; then
var="after"
echo "$var" #first echo
fi
done < <(echo "$someString" | sed '$someRegex')
echo "$var" #second echo
最佳答案
此行为的原因是 while
循环在作为管道的一部分时在子 shell 中运行。对于上面的 while
循环,创建了一个新的子 shell,它有自己的变量 var
副本。
有关可能的解决方法,请参阅本文:I set variables in a loop that's in a pipeline. Why do they disappear after the loop terminates? Or, why can't I pipe data to read? .
关于linux - 不能在 bash 中使用 while 和 pipe 中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6572411/