使用“读取”访问 Bash 管道的输出

Kar*_*hik 7 bash

我正在尝试使用 read 命令将一些数据从 Bash 管道传输到 Bash 变量中,如下所示:

$ echo "Alexander the Grape" | read quot
$ echo $quot
$ 
Run Code Online (Sandbox Code Playgroud)

但是 quot 是空的。一些谷歌搜索显示这不是一个错误;这是 Bash 的一个预期功能。(常见问题解答中的 E5部分。)

但是当我在 zsh 中尝试同样的事情时,它奏效了。(ksh 同上。)有什么办法可以在 Bash 中完成这项工作?我真的不想输入:

$ quot=$(echo "Alexander the Grape")
Run Code Online (Sandbox Code Playgroud)

特别是对于长命令。

Den*_*son 4

有关此主题的更多阅读,请参阅BashFAQ/024

在 Bash 中进行变量赋值有多种方法:

var=$(command)
read var <<< $(command)
read var <<< EOF
$(command)
EOF
printf -v var "%s" $(command)
Run Code Online (Sandbox Code Playgroud)

ETC。