shell while循环后变量的值未变化

 工作中想遍历文件中的每行,并且赋值给一个变量,使用下面写法,但是循环遍历后变量依然为空,值没有变化。如下:

~/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

发布了41 篇原创文章 · 获赞 14 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/liurizhou/article/details/100078917