本文介绍了在while循环外无法读取在while循环内存储的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我一生都无法理解为什么我无法在 while 循环之外读取 postPrioity.我试过 "export postPrioity="500"" 还是不行.
I can't for the life of me see why I can not read the postPrioity outside the while loop.I tried "export postPrioity="500"" still didn't work.
有什么想法吗?
-- 或在计划文本中 --
-- 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"
输出:(我在files.txt中只有3个文件名)
OUTPUT: (I only have 3 file names in files.txt)
weeeeeeeeee ---> 500 <--- 1
weeeeeeeeee ---> 500 <--- 1
weeeeeeeeee ---> 500 <--- 1
weeeeeeeeee ---> <--- 2
推荐答案
管道操作符创建子shell,参见BashPitfalls 和 BashFAQ.解决办法:不要用cat
,反正也没用.
The pipe operator creates a subshell, see BashPitfalls and BashFAQ. Solution: Don't use cat
, it's useless anyway.
#!/bin/bash
postPriority=0
while read namesInFile
do
postPrioity=500
echo "weeeeeeeeee ---> $postPrioity <--- 1"
done < /files.txt
echo "weeeeeeeeee ---> $postPrioity <--- 2"
这篇关于在while循环外无法读取在while循环内存储的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!