bash - 为什么 bash 中的 read 命令可以使用这里字符串,但不能使用管道输出?

标签 bash input pipe herestring

我试图了解 bash read 命令在幕后是如何工作的。 鉴于它期望其输入来自标准输入,我惊讶地发现管道输入无法按预期工作。例如

### Pipe scenario

echo "1 2 3" | read -r one two three
echo "one: $one, two: $two, three: $three"
# output:   'one: , two: , three:' 

### Herestring scenario

read -r one two three <<< "1 2 3"
echo "one: $one, two: $two, three: $three"
# output:   'one: 1, two: 2, three: 3'

有人可以解释一下上述两种提供输入的方式有何不同(从读取命令的角度来看)?



编辑回应评论:

我不想知道“如何解决通过管道传递输入”,就像评论中的链接问题一样。我知道该怎么做(例如我可以使用这里字符串!)。

我的问题是,使读取在两种情况下表现不同的底层机制是什么?

最佳答案

read 可以工作,但您需要在同一子 shell 中请求值:

echo "1 2 3" | (read -r one two three && echo "one: $one, two: $two, three: $three")

另一种选择是

read -r one two three < <( echo "1 2 3")

关于bash - 为什么 bash 中的 read 命令可以使用这里字符串,但不能使用管道输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61631695/

相关文章:

html - jsp - 从 java 字符串设置输入标签 (html) 的值

c++ - 编写一个循环以更改具有不同名称的 int 数组中的值

linux - 在 bash 进程替换完成输入后,如何继续发送到标准输入?

java - 运行 java exec 命令,总是需要应用程序的完整绝对路径?

linux - 使用文字双引号从 bash 脚本生成文本

python - 使用 appcfg.py/bulkloader.py 和脚本进行远程备份。如何处理电子邮件/密码字段?

python - 遍历类文件和调用 readline 之间的区别

macos - Mac终端发送带附件的邮件

bash - 如何将用户输入读入 Bash 中的变量?

python - 子进程 - 使用几个命令行工具