標籤:command 單引號 default 雙引號 performing
一、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 處理"命令替換"和"參數替換"時,shell 根據 IFS 的值,預設是 space, tab, newline 來拆解讀入的變數,然後對特殊字元進行處理,最後重新組合賦值給該變數。
對於IFS的使用,唯一的途徑,就是瞭解shell的執行順序。在《shell指令碼學習指南》第7章,179頁,有個圖,說的很清晰明了。在命令列上,對單引號字串、雙引號字串、不帶引號字串的引用如何處理都講的很清晰,以及IFS分隔字串的時機。
總體上記住一點,雙引號和單引號字串引用可以屏蔽對命令參數使用IFS分割。
650) this.width=650;" src="http://s3.51cto.com/wyfs02/M01/47/0E/wKiom1P19HziCeSLAAJeUKSJVl0900.jpg" title="1.png" alt="wKiom1P19HziCeSLAAJeUKSJVl0900.jpg" />
如所示,shell命令被解析執行的順序。在第①步和第⑨步,都會進行一個 split 操作。在第①步中,我們在命令列上輸入命令,然後shell首先會把它們以IFS作為分隔字元split為token, 然後到了第⑨步中,參數擴充和命令替換後的結果也會被以IFS為分隔字元,split為word。
以下是值得注意的地方:
IFS is the space, tab, and newline characters by default,連續多個空白被看做一個處理
"$*" 使用IFS中的第一個字元作為分隔字元,把參數串連
awk中的FS(域分隔字元)也和IFS有類似的用法和作用
二、IFS 簡單一實例
1、查看IFS的值
[[email protected] ~]# set | grep IFSIFS=$‘ \t\n‘[[email protected] ~]# echo -n "$IFS" | od -ab0000000 sp ht nl 040 011 0120000003
2、"[email protected]" 和 "$*" 異同
* Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, it expands to a single word with the value of each parameter separated by the first character of the IFS special variable. That is, "$*" is equivalent to "$1c$2c...", where c is the first character of the value of the IFS variable. If IFS is unset, the parameters are separated by spaces. If IFS is null, the parameters are joined without intervening separators.
@ Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, each parameter expands to a separate word. That is, "[email protected]" is equivalent to "$1" "$2" ... If the double-quoted expansion occurs within a word, the expansion of the first parameter is joined with the beginning part of the original word, and the expansion of the last parameter is joined with the last part of the original word. When there are no positional parameters, "[email protected]" and [email protected] expand to nothing (i.e., they are removed).
"[email protected]" "$*" 只有當用雙引號quoting時, 它們才有所不同。[email protected] $* 兩種結果是相同的。
本文出自 “Share your knowledge” 部落格,請務必保留此出處http://skypegnu1.blog.51cto.com/8991766/1543319