read 帶一個引數和不帶引數的區別是什麼,我本以為僅僅是被賦值的變數的名字不同而已:
$ read name 1 $ echo "$name" 1 $ read 1 $ echo "$REPLY" 1 |
當沒有指定變數名時,read 會給預設的變數 REPLY 賦值,僅此而已。然而今天我卻發現個細微的區別(下面為了顯示空格故意加了背景色):
$ read name 1 $ echo "$name" 1 $ read 1 $ echo "$REPLY" 1 |
看到了吧,當你使用自定義的變數名時,使用者輸入的字串中開頭和尾部的 IFS 空白符都會被 strip 掉,而使用預設的 REPLY 變數時,就不會有這個操作。我翻了下 Bash 原始碼,找到了一段專門為這個行為寫的註釋:
/* If there are no variables, save the text of the line read to the
variable $REPLY. ksh93 strips leading and trailing IFS whitespace,
so that `read x ; echo "$x"' and `read ; echo "$REPLY"' behave the
same way, but I believe that the difference in behaviors is useful
enough to not do it. Without the bash behavior, there is no way
to read a line completely without interpretation or modification
unless you mess with $IFS (e.g., setting it to the empty string).
If you disagree, change the occurrences of `#if 0' to `#if 1' below. */
也就是說,Bash 作者覺的,應該留一個方便的,不用改 IFS 就能讓 Shell 能獲取到使用者完整的輸入的字串的小技巧。裡面也說了,ksh 沒有這個特殊處理,這是 Bash 自己發明的小把戲。