- 論壇徽章:
- 0
|
在編寫shell腳本的時候,時常會碰到IFS變量,但我對于具體的使用和設置常常比較模糊,今天花了一點時間googel和實驗了一下,總結如下:
(1)什么是IFS ?
IFS是bash的內部變量,稱為內部域分隔符.這個變量用來決定Bash在解釋字符串時如何識別域,或者單詞邊界.
(2)如何查看當前的IFS值?
tekkaman@tekkaman-desktop:~/working/abs_test/IFS$ echo "$IFS"
由于IFS默認為空白(空格,tab和新行),所以使用以上的命令似乎看不到字符。沒關系,你可以用od命令看16進制,或是2進制值:
tekkaman@tekkaman-desktop:~/working/abs_test/IFS$ echo "$IFS" | od -t x1
0000000 20 09 0a 0a
0000004
注意:$*使用$IFS 中的第一個字符,比如:
tekkaman@tekkaman-desktop:~/working/abs_test/IFS$ set w x y z;echo "$*"
w x y z
(3)如何修改IFS值?
普通的賦值命令即可:
tekkaman@tekkaman-desktop:~/working/abs_test/IFS$ IFS=":"
tekkaman@tekkaman-desktop:~/working/abs_test/IFS$ echo "$IFS"
:
tekkaman@tekkaman-desktop:~/working/abs_test/IFS$ echo "$IFS" | od -t x1
0000000 3a 0a
0000002
tekkaman@tekkaman-desktop:~/working/abs_test/IFS$ set w x y z;echo "$*"
w:x:y:z
(4)實驗:$*使用$IFS 中的第一個字符
tekkaman@tekkaman-desktop:~/working/abs_test/IFS$ IFS="\\:;"
tekkaman@tekkaman-desktop:~/working/abs_test/IFS$ echo "$IFS"
\:;
tekkaman@tekkaman-desktop:~/working/abs_test/IFS$ echo "$IFS" | od -t x1
0000000 5c 3a 3b 0a
0000004
tekkaman@tekkaman-desktop:~/working/abs_test/IFS$ set w x y z;echo "$*"
w\x\y\z
tekkaman@tekkaman-desktop:~/working/abs_test/IFS$ IFS=":;\\"
tekkaman@tekkaman-desktop:~/working/abs_test/IFS$ echo "$IFS"
:;\
tekkaman@tekkaman-desktop:~/working/abs_test/IFS$ echo "$IFS" | od -t x1
0000000 3a 3b 5c 0a
0000004
tekkaman@tekkaman-desktop:~/working/abs_test/IFS$ set w x y z;echo "$*"
w:x:y:z
(5)備份IFS
tekkaman@tekkaman-desktop:~/working/abs_test/IFS$ echo "$IFS" | od -t x1
0000000 20 09 0a 0a
0000004
tekkaman@tekkaman-desktop:~/working/abs_test/IFS$ OLDIFS="$IFS"
tekkaman@tekkaman-desktop:~/working/abs_test/IFS$ echo "$OLDIFS" | od -t x1
0000000 20 09 0a 0a
0000004
tekkaman@tekkaman-desktop:~/working/abs_test/IFS$ IFS=":"
tekkaman@tekkaman-desktop:~/working/abs_test/IFS$ echo "$IFS" | od -t x1
0000000 3a 0a
0000002
tekkaman@tekkaman-desktop:~/working/abs_test/IFS$ IFS="$OLDIFS"
tekkaman@tekkaman-desktop:~/working/abs_test/IFS$ echo "$IFS" | od -t x1
0000000 20 09 0a 0a
0000004
參考資料:
《[精彩] 關于IFS的疑問》
《ABS 3.7.2中文版》翻譯:楊春敏 黃毅
本文來自ChinaUnix博客,如果查看原文請點:http://blog.chinaunix.net/u1/34474/showart_2002264.html |
|