[英]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.