工作中想遍历文件中的每行,并且赋值给一个变量,使用下面写法,但是循环遍历后变量依然为空,值没有变化。如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
$ cat temp.txt http://www.baidu.com http://www.jd.com http://www.huawei.com $ 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}+++++" $ source temp.sh http://www.baidu.com_____ http://www.jd.com_____ http://www.huawei.com_____ +++++ |
上面未赋值成功是因为使用了管道符,将值传给了while,使得while在子shell中执行,子shell中的变量等在循环外无效。
可以写为:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
$ 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}+++++" $ 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;+++++ |
或者:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
$ 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}+++++" $ 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;+++++ |
或者指定换行符读取:
1 2 3 4 5 6 7 8 9 |
#! /bin/bash IFS=" " for LINE in `cat /etc/passwd` do echo $LINE done |
或者用read读取文件重定向:
1 2 3 4 5 6 |
#! /bin/bash while read LINE do echo $LINE done < /etc/passwd |