概述
工作中想遍历文件中的每行,并且赋值给一个变量,使用下面写法,但是循环遍历后变量依然为空,值没有变化。如下:
~/temp/201908/temp/temp$ cat temp.txt
http://www.baidu.com
http://www.jd.com
http://www.huawei.com
~/temp/201908/temp/temp$ cat temp.sh
#! /bin/bash
file_path=temp.txt
new_var=''
cat ${file_path} | while read line
do
new_var="${new_var}${line};"
echo ${line}_____
done
echo "${new_var}+++++"
~/temp/201908/temp/temp$ source temp.sh
http://www.baidu.com_____
http://www.jd.com_____
http://www.huawei.com_____
+++++
上面未赋值成功是因为使用了管道符,将值传给了while,使得while在子shell中执行,子shell中的变量等在循环外无效。
可以写为:
~/temp/201908/temp/temp$ cat temp.sh
#! /bin/bash
file_path=temp.txt
new_var=''
while read line
do
new_var="${new_var}${line};"
echo ${line}_____
done <<< "$(cat ${file_path})"
echo "${new_var}+++++"
~/temp/201908/temp/temp$ source temp.sh
http://www.baidu.com_____
http://www.jd.com_____
http://www.huawei.com_____
http://www.baidu.com;http://www.jd.com;http://www.huawei.com;+++++
或者:
~/temp/201908/temp/temp$ cat temp.sh
#! /bin/bash
file_path=temp.txt
new_var=''
while read line
do
new_var="${new_var}${line};"
echo ${line}_____
done < ${file_path}
echo "${new_var}+++++"
~/temp/201908/temp/temp$ source temp.sh
http://www.baidu.com_____
http://www.jd.com_____
http://www.huawei.com_____
http://www.baidu.com;http://www.jd.com;http://www.huawei.com;+++++
参考:https://www.cnblogs.com/f-ck-need-u/p/7431578.html
最后
以上就是完美秋天为你收集整理的shell while循环后变量的值未变化的全部内容,希望文章能够帮你解决shell while循环后变量的值未变化所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复