1

我一生都无法理解为什么我无法在 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
4

3 回答 3

9

管道运算符创建一个子外壳,请参阅BashPitfallsBashFAQ。解决方法:不要用cat,反正也没用。

#!/bin/bash
postPriority=0
while read namesInFile
do   
    postPrioity=500
    echo "weeeeeeeeee ---> $postPrioity <--- 1"
done < /files.txt
echo "weeeeeeeeee ---> $postPrioity <--- 2"
于 2009-10-07T06:08:13.013 回答
7

作为 Philipp 响应的补充,如果您必须使用管道(正如他所指出的,在您的示例中您不需要 cat),您可以将所有逻辑放在管道的同一侧:


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

于 2009-10-07T07:52:52.730 回答
1

或者使用进程替换:

while read line
do    
    variable=value  
done < <(command)
于 2009-10-07T10:28:51.570 回答