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

标签 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 中没有空格,因此我不希望 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/

相关文章:

mysql - 如何从 bash 脚本中有效地处理 mysql 的结果集?

bash - bash 内置 printf 的 %a 格式说明符是什么?

linux - 使用批处理文件或 shell 脚本进行文件传输

linux - 无法创建备份文件(添加!覆盖)

bash - zsh:动态生成字符串的bash脚本比较

mysql - 如何使用 bash 将字符添加到 CSV 中每条记录的可变数量字段?

linux - 如何将awk结果输出到文件

bash - Busybox sh 不会执行 bash 脚本

ruby-on-rails - 在终端输出上播放声音

bash - 运行 bash,在 "bash XXX.sh"命令中包含一个变量