[英]Can't read variable that was stored from within a while loop, when out of the while loop
我一生无法理解为什么我无法在while循环之外阅读postPrioity。 我尝试过“ export postPrioity =“ 500””仍然无法正常工作。
有任何想法吗?
-或在计划文字中-
#!/bin/bash
cat "/files.txt" | while read namesInFile; do
postPrioity="500"
#This one shows the "$postPrioity" varible, as '500'
echo "weeeeeeeeee ---> $postPrioity <--- 1"
done
#This one comes up with "" as the $postPrioity varible. GRRR
echo "weeeeeeeeee ---> $postPrioity <--- 2"
输出:(我在files.txt中只有3个文件名)
weeeeeeeeee ---> 500 <--- 1
weeeeeeeeee ---> 500 <--- 1
weeeeeeeeee ---> 500 <--- 1
weeeeeeeeee ---> <--- 2
管道操作员创建一个子外壳,请参阅BashPitfalls和BashFAQ 。 解决方案:不要使用cat
,无论如何它是没有用的。
#!/bin/bash
postPriority=0
while read namesInFile
do
postPrioity=500
echo "weeeeeeeeee ---> $postPrioity <--- 1"
done < /files.txt
echo "weeeeeeeeee ---> $postPrioity <--- 2"
作为对Philipp响应的补充,万一您必须使用管道(正如他指出的,在您的示例中您不需要cat),则可以将所有逻辑放在管道的同一侧:
command | {
while read line; do
variable=value
done
# Here $variable exists
echo $variable
}
# Here it doesn't
或者使用流程替换:
while read line
do
variable=value
done < <(command)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.