1. 程式人生 > >SHELL中的IFS詳解

SHELL中的IFS詳解

在bash中IFS是內部的域分隔符,manual中對其的敘述如下:
IFS The Internal Field Separator that is used for word splitting after expansion and to split lines into words with the read builtin command. The default value is  ”.
如下是一些值得注意的地方。
1. IFS的預設值為:空白(包括:空格,tab, 和新行),將其ASSII碼用十六進位制打印出來就是:20 09 0a (見下面的shell指令碼)。
2. IFS對空格的空白的處理和其他字元不一樣,左右兩邊的純空白會被忽略,多個連續的空白被當成一個IFS處理。
3. S*中使用IFS中的第一個字元。
4. awk中的FS(域分隔符)也和IFS有類似的用法和作用。

我寫了一個shell指令碼來演示IFS的用法和作用,如下:

[[email protected] test]$ IFS=''

[[email protected] test]$ set foo bar bam

[[email protected] test]$ echo "[email protected]"
foo bar bam
[[email protected] test]$ echo "$*"
foobarbam
[[email protected] test]$ unset IFS
[[email protected]

test]$ echo "$*"
foo bar bam


[[email protected] test]$ IFS=a
[[email protected] test]$ echo "[email protected]"
foo bar bam
[[email protected] test]$ echo "$*"
fooabarabam
[[email protected] test]$ unset IFS
[[email protected] test]$ echo "$*"
foo bar bam


$* 是在一個變數中列出所有的引數,各個引數之間用環境變數IFS中的第一個字元分隔開。如果IFS被修改了,那麼$*將命令列分割為引數的方式就改變。

[email protected] 不使用IFS環境變數。

一般來說訪問指令碼程式的引數,使用[email protected]是明智的選擇。