2009-10-07 96 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)