Bash:将命令输出重定向到 STDOUT 和变量

jcs*_*jcs 2 bash io-redirection shell-script

在 Bash 脚本中,我需要将命令的输出重定向到变量,同时还将无缓冲的输出流式传输到终端。

我试过这个:

output=$(command 2>&1 | tee "$(tty)")
Run Code Online (Sandbox Code Playgroud)

但这不会向终端输出任何内容。

我也试过

mytty=$(tty)
output=$(command 2>&1 | tee $mytty)
Run Code Online (Sandbox Code Playgroud)

这给了我错误“tee:/dev/tty1:权限被拒绝”。

当前的操作系统是 OpenSUSE 15.0,我没有 sudo/root 权限。

ImH*_*ere 5

尝试

... | tee /dev/tty
Run Code Online (Sandbox Code Playgroud)

喜欢:

output=$( command 2>&1 | tee /dev/tty )
Run Code Online (Sandbox Code Playgroud)

该命令tty在管道内不起作用:

$ echo $(tty)           # or (a lot better) simply:  tty
/dev/pts/4

$ echo aa | echo $(tty)
not a tty
Run Code Online (Sandbox Code Playgroud)

这意味着管道的右侧没有连接到 tty。