read name 和 read 在 Bash 中的区别

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 自己发明的小把戏。

posted @ 2015-10-19 17:49  紫云飞  阅读(1048)  评论(0编辑  收藏  举报