bash read命令将行拆分为使用空格作为分隔符的单词,即使空间不在IFS中也是如此

时间:2014-09-14 17:51:55

标签: bash

我正在使用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中,我不希望读取将字符串"foo bar baz"分成三个单词。但阅读确实将其分为三个单词。

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

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

2 个答案:

答案 0 :(得分:4)

这很可能只是echo IFS

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

答案 1 :(得分:0)

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

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]