我有这个示例代码:
find "$1" ! -regex "$regex" 2>/dev/null | while read line ; do
a="$line"
done
echo ("$a") # prints nothing because of subshell
我需要:
$a
在外部可见(在全局范围内)我怎样才能做到这一点?有没有简单的解决方案?
答案 0 :(得分:4)
如果我理解正确的话,那就不是那么困扰你的子shell,而是变量不会在子shell之外保留其值的事实。 您可以使用这样的代码分组:
find "$1" ! -regex "$regex" 2>/dev/null |
{
while read line
do
a=$line
done
echo "$a"
}
您可以使用变量a
的值,只要它在花括号内即可。
答案 1 :(得分:1)
使用显式命名管道。
mkfifo named_pipe
find "$1" ! -regex "$regex" 2> /dev/null > named_pipe &
while read line; do
a=$line
done < named_pipe
答案 2 :(得分:0)
如果没有命名管道且没有在子shell中运行整个事件,您可以在here-doc中使用here-doc command substitution:
<div id="products_main">
<div id="products">
<div class="product_item">
<div>
<h2 class="product_item_heading">
Industrial Automation
</h2>
</div>
<div class="product_item_image">
<img src="images/products/Industrial automation/images/Oscillator.jpg" width="350" height="200">
</div>
<div class="product_item_content">
Oscillators:Quartz crystal Oscillators,crystal resonators,Oscillator modules for defence & Space applications will be supplied with custom-made.Oscillators like TCXO,VCXO,OCXO etc.
</div>
</div>
</div>
</div>
这应该是便携式的。
另见。 BashFAQ/024。
注意。像这样解析while read line; do
a=$line
done <<EOF
$(find "$1" ! -regex "$regex" 2>/dev/null)
EOF
echo "$a"
的输出是一个反模式。