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 (编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|