我不能为我的生活看到为什么我不能阅读while循环之外的postPrioity。 我试过“出口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
管道操作员创建一个子shell,请参阅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
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)