在bash不能使用变量出来,而与管 [英] Can't use a variable out of while and pipe in bash
问题描述
我有一个code一样,
VAR =之前
回声$ someString| SED'$ someRegex|而读线
做
如果[$条件];然后
VAR =后
回声$ VAR#first回声
科幻
DONE
回声$ VAR#second回声
下面第一回声打印后,但第二个是之前。我怎样才能让第二回声打印之后。我认为这是因为管我买的不知道该怎么搞清楚。
感谢您的任何解决方案...
答案编辑:
我纠正它,它工作正常。尤金感谢您有用的答案
VAR =之前
而读线
做
如果[$条件];然后
VAR =后
回声$ VAR#first回声
科幻
完成< ≤(回声$ someString| sed的'$ someRegex')
回声$ VAR#second回声
这样做的原因行为是一个,而
循环中时,它的管道的一部分子shell运行。对于上面的,而
循环,有自己的变量拷贝一个新的子shell VAR
创建
请参阅本文可能的解决方法:我设置的变量在一个循环,是在一个管道。为什么他们消失在循环终止后?或者说,为什么我不能管数据看?。
I have a code like that
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
Here first echo print "after", but second is "before". How can I make second echo print "after". I think it is because of pipe buy I don't know how figure out.
Thanks for any solutions...
answer edit:
I corrected it and it works fine. Thanks eugene for your useful answer
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
The reason for this behaviour is that a while
loop runs in a subshell when it's part of a pipeline. For the while
loop above, a new subshell with its own copy of the variable var
is created.
See this article for possible workarounds: 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?.
这篇关于在bash不能使用变量出来,而与管的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!