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

  • 相关阅读:
    NOI2015刷题记录
    [WC2013][UOJ58]糖果公园 莫队算法
    啦啦啦~
    完全平方数
    构建之法
    测试更新
    程序的测试
    程序的封装
    构建之法5.5-6-7章观后感
    给徐侃童鞋的一个汉堡
  • 原文地址:https://www.cnblogs.com/ziyunfei/p/4848383.html
Copyright © 2020-2023  润新知