2009-10-07 142 views
1

我不能在我的生活中看到爲什麼我無法讀取while循環之外的postPrioity。 我試過「export postPrioity =」500「」仍然沒有工作。無法讀取while循環中存儲的變量,當出現while循環時

任何想法?

- 或計劃文本 -

#!/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" 

OUTPUT:(我只有在files.txt 3文件名)

weeeeeeeeee ---> 500 <--- 1 
weeeeeeeeee ---> 500 <--- 1 
weeeeeeeeee ---> 500 <--- 1 
weeeeeeeeee ---> <--- 2 

回答

9

管道運營商創建一個子shell,看到BashPitfallsBashFAQ。解決方案:不要使用cat,反正無用。

#!/bin/bash 
postPriority=0 
while read namesInFile 
do 
    postPrioity=500 
    echo "weeeeeeeeee ---> $postPrioity <--- 1" 
done < /files.txt 
echo "weeeeeeeeee ---> $postPrioity <--- 2" 
+0

感謝證實我的猜測!我想在BashFAQ中提到的其他一些解決方法(例如命令分組)是更好的選擇,但通常你的管道並不是毫無意義的。 – Cascabel 2009-10-07 06:12:02

+1

當然,管道在每種情況下都不是毫無意義,但是構造「cat file | ...「應該在大多數情況下被替換爲」... <文件「。見例如Bash指南:http://mywiki.wooledge.org/BashGuide#BashGuide.2BAC8-Practices.2BAC8-DontEverDoThese.Don.27t_Ever_Do_These – Philipp 2009-10-07 06:18:00

+0

從來不知道這一點,你我知道一些關於subshel​​l的。 但是,現在請記住這一點,並將在這些網站上閱讀,謝謝。 – Mint 2009-10-07 06:24:10

6

爲補充菲利普的反應,如果你必須使用一個管道(和他指出,在你的榜樣,你不需要貓),你可以把所有的邏輯的同一側管道:

 

command | { 
    while read line; do 
    variable=value 
    done 
    # Here $variable exists 
    echo $variable 
} 
# Here it doesn't 
 
1

或者使用過程中替換:

while read line 
do  
    variable=value 
done < <(command)