簡體   English   中英

在while循環外時,無法讀取從while循環內存儲的變量

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

管道操作員創建一個子外殼,請參閱BashPitfallsBashFAQ 解決方案:不要使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM