我试图了解 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/