简体   繁体   English

在while循环外时,无法读取从while循环内存储的变量

[英]Can't read variable that was stored from within a while loop, when out of the while loop

I can't for the life of me see why I can not read the postPrioity outside the while loop. 我一生无法理解为什么我无法在while循环之外阅读postPrioity。 I tried "export postPrioity="500"" still didn't work. 我尝试过“ export postPrioity =“ 500””仍然无法正常工作。

Any ideas? 有任何想法吗?

-- or in plan text -- -或在计划文字中-

#!/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: (I only have 3 file names in files.txt) 输出:(我在files.txt中只有3个文件名)

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

The pipe operator creates a subshell, see BashPitfalls and BashFAQ . 管道操作员创建一个子外壳,请参阅BashPitfallsBashFAQ Solution: Don't use cat , it's useless anyway. 解决方案:不要使用cat ,无论如何它是没有用的。

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

As a complement to Philipp's response, in case you MUST use a pipe (and as he pointed out, in your example you don't need cat), you can put all the logic in the same side of the pipe: 作为对Philipp响应的补充,万一您必须使用管道(正如他指出的,在您的示例中您不需要cat),则可以将所有逻辑放在管道的同一侧:


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

Alternatively use process substitution: 或者使用流程替换:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM