工作中想遍历文件中的每行,并且赋值给一个变量,使用下面写法,但是循环遍历后变量依然为空,值没有变化。如下:
~/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;+++++