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/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