当不在while循环中时,无法读取while循环中存储的变量

Min*_*int 1 linux bash shell 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"
Run Code Online (Sandbox Code Playgroud)

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

weeeeeeeeee ---> 500 <--- 1
weeeeeeeeee ---> 500 <--- 1
weeeeeeeeee ---> 500 <--- 1
weeeeeeeeee --->  <--- 2
Run Code Online (Sandbox Code Playgroud)

Phi*_*ipp 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"
Run Code Online (Sandbox Code Playgroud)


Ide*_*lic 6

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


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