为什么bash中的read命令只能使用herestring,而不能使用管道输出?

问题描述 投票:0回答:1

我正在尝试了解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'

有人可以解释以上两种提供输入的方式(从读取命令的角度来看)有何根本区别吗?

bash input pipe herestring
1个回答
1
投票

read有效,但是您需要在同一子shell中询问值:

echo "1 2 3" | (read -r one two three && echo "one: $one, two: $two, three: $three")
© www.soinside.com 2019 - 2024. All rights reserved.