1. 程式人生 > >shell中IFS用法

shell中IFS用法

 一 IFS的介紹
   Shell 指令碼中有個變數叫IFS(Internal Field Seprator) ,內部域分隔符。完整定義是The shell uses the value stored in IFS, which is the space, tab, and newline characters by default, to delimit words for the read and set commands, when parsing output from command substitution, and when performing variable substitution.

   Shell 的環境變數分為set, env 兩種,其中 set 變數可以通過 export 工具匯入到 env 變數中。其中,set 是顯示設定shell變數,僅在本 shell 中有效;env 是顯示設定使用者環境變數 ,僅在當前會話中有效。換句話說,set 變數裡包含了env 變數,但set變數不一定都是env 變數。這兩種變數不同之處在於變數的作用域不同。顯然,env 變數的作用域要大些,它可以在 subshell 中使用。
   IFS 是一種 set 變數,當 shell 處理"命令替換"和"引數替換"時,shell 根據 IFS 的值,預設是 space, tab, newline 來拆解讀入的變數,然後對特殊字元進行處理,最後重新組合賦值給該變數。

二 IFS的簡單例項
1 檢視IFS的值
echo "$IFS"

echo "$IFS"|od -b
0000000 040 011 012 012 

0000004

直接輸出IFS是看不到值的,轉化為二進位制就可以看到了,"040"是空格,"011"是Tab,"012"是換行符"\n" 。最後一個 012 是因為 echo 預設是會換行的。
2 實際中的應用
#!/bin/bash
OLD_IFS=$IFS #儲存原始值
IFS="" #改變IFS的值
...
...
IFS=$OLD_IFS #還原IFS的原始值