zhuce 发表于 2018-8-26 11:21:24

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

  shell把每个 $IFS 字符对待成一个分隔符,且基于这些字符把其他扩展的结果分割。如果 IFS 未设置,或者它的值正好是 “‘’”,那么任何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/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

页: [1]
查看完整版本: shell中字分隔的妙用:变量IFS