我正在使用 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=$'\t\n '
> echo $IFS | od -tcx1
0000000 \n
0a
0000001
> echo -n "$IFS" | od -tcx1
0000000 \t \n
09 0a 20
0000003
关于bash read 命令使用空格作为分隔符将行分割成单词,即使空格不在 IFS 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25836222/