文章出處

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 自己發明的小把戲。


文章列表




Avast logo

Avast 防毒軟體已檢查此封電子郵件的病毒。
www.avast.com


全站熱搜
創作者介紹
創作者 大師兄 的頭像
大師兄

IT工程師數位筆記本

大師兄 發表在 痞客邦 留言(0) 人氣()