bash-read命令使用空格作为分隔符将行拆分为单词,即使空格不在IFS中



我正在使用bash。

$ bash --version
GNU bash, version 4.3.11(1)-release (x86_64-pc-linux-gnu)
Copyright (C) 2013 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
From `help read`

这就是help read的前几行所说的:

$ help read | head
read: read [-ers] [-a array] [-d delim] [-i text] [-n nchars] [-N nchars] [-p prompt] [-t timeout] [-u fd] [name ...]
    Read a line from the standard input and split it into fields.
    Reads a single line from the standard input, or from file descriptor FD
    if the -u option is supplied.  The line is split into fields as with word
    splitting, and the first word is assigned to the first NAME, the second
    word to the second NAME, and so on, with any leftover words assigned to
    the last NAME.  Only the characters found in $IFS are recognized as word
    delimiters.

我的IFS只是一个换行符,即n

$ echo $IFS
$ echo $IFS | od -tcx1                                                                                     
0000000  n
         0a
0000001

由于空间不在IFS中,所以我不希望read将字符串"foo bar baz"拆分为三个单词。但read确实把它分成了三个单词。

$ read a b c <<< "foo bar baz"; echo $a; echo $b; echo $c
foo
bar
baz

当空格不在我的IFS中时,为什么它使用空格作为分隔符来分割字符串?

这很可能只是echo IFS 的问题

> IFS=$'tn '
> echo $IFS | od -tcx1
0000000  n
         0a
0000001
> echo -n "$IFS" | od -tcx1
0000000  t  n
         09  0a  20
0000003

这看起来不对。这样测试:

bash --version
GNU bash, version 4.2.45(2)-release (i386-apple-darwin13.1.0)
Copyright (C) 2011 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
IFS=$'n' read a b c <<< "foo bar baz"; echo "a=[$a]"; echo "b=[$b]"; echo "c=[$c]"
a=[foo bar baz]
b=[]
c=[]
unset IFS
read a b c <<< "foo bar baz"; echo "a=[$a]"; echo "b=[$b]"; echo "c=[$c]"
a=[foo]
b=[bar]
c=[baz]

最新更新