shell中字分隔的妙用:变量IFS

shell把每个$IFS字符对待成一个分隔符,且基于这些字符把其他扩展的结果分割。如果IFS未设置,或者它的值正好是 “‘<space><tab><newline>’”,那么任何IFS字符的序列就送往分割字。

自写一个简单的脚本:
#!/bin/bash
for i in `cat /etc/passwd`
do
echo $i
done
输出结果:
test33:x:506:100::/home/test33:/bin/bash
test44:x:507:512::/home/test44:/bin/bash
test55:x:508:100::/home/test55:/bin/bash
test66:x:509:100::/home/test66:/bin/bash

假如/etc/passwd中有第五列,即注释,恰恰注释中包含空格,如下:
test33:x:506:100::/home/test33:/bin/bash
test44:x:507:512::/home/test44:/bin/bash
test55:x:508:100::/home/test55:/bin/bash
test66:x:509:100:user test1:/home/test66:/bin/bash

执行的结果是什么呢,乱了:
test33:x:506:100::/home/test33:/bin/bash
test44:x:507:512::/home/test44:/bin/bash
test55:x:508:100::/home/test55:/bin/bash
test66:x:509:100:user
test1:/home/test66:/bin/bash

程序把注释中的空格看作字分隔符了。为了解决这一问题,可用$IFS变量:
#!/bin/bash
IFS_old=$IFS #将原IFS值保存,以便用完后恢复
IFS=$’\n’ #更改IFS值为$’\n’ ,注意,以回车做为分隔符,IFS必须为:$’\n’
for i in `cat m.txt`
do
echo $i
done
IFS=$IFS_old #恢复原IFS值

再次运行,得到预期结果:test33:x:506:100::/home/test33:/bin/bashtest44:x:507:512::/home/test44:/bin/bashtest55:x:508:100::/home/test55:/bin/bashtest66:x:509:100:user test1:/home/test66:/bin/bash

相关文章

用的openwrt路由器,家里宽带申请了动态公网ip,为了方便把2...
#!/bin/bashcommand1&command2&wait从Shell脚本并行...
1.先查出MAMP下面集成的PHP版本cd/Applications/MAMP/bin/ph...
1、先输入locale-a,查看一下现在已安装的语言2、若不存在如...
BashPerlTclsyntaxdiff1.进制数表示Languagebinaryoctalhexa...
正常安装了k8s后,使用kubect工具后接的命令不能直接tab补全...