bash 如何在打印输出的同时将命令的输出存储在变量中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37067895/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 14:35:59  来源:igfitidea点击:

How to store the output of a command in a variable at the same time as printing the output?

bashstdoutgnu

提问by fedorqui 'SO stop harming'

Say I want to echosomething and capture it in a variable, at the same time I see it in my screen.

假设我想要echo一些东西并将其捕获在一个变量中,同时我在屏幕上看到它。

echo "hello" | tee tmp_file
var=$(< tmp_file)

So now I could see helloin my terminal as well as saving it into the variable $var.

所以现在我可以hello在我的终端中看到并将其保存到变量中$var

However, is there any way to do this without having to use a temporary file? teedoesn't seem to be the solution, since it says (from man tee) read from standard input and write to standard output and files, whereas here it is two times standard output.

但是,有没有什么方法可以在不必使用临时文件的情况下做到这一点?tee似乎不是解决方案,因为它说 (from man tee)从标准输入读取并写入标准输出和文件,而这里是标准输出的两倍。

I am in Bash 4.3, if this matters.

如果这很重要,我在 Bash 4.3 中。

回答by 123

Use tee to direct it straight to screen instead of stdout

使用 tee 将其直接引导到屏幕而不是 stdout

$ var=$(echo hi | tee /dev/tty)
hi
$ echo $var
hi

回答by Leo

Pipe teedoes the trick.

管道tee可以解决问题。

This is my approach addressed in this question.

这是我在这个问题中解决的方法。

var=$(echo "hello" | tee /dev/tty)

Then you can use $varto get back the stored variable.

然后你可以使用$var来取回存储的变量。

For example:

例如:

var=$(echo "hello" | tee /dev/tty); echo "$var world"

Will output:

将输出:

hello
hello world

You can do more with pipes, for example I want to print a phrase in the terminal, and at the same time tell how many "l"s are there in it:

您可以使用管道做更多事情,例如我想在终端中打印一个短语,同时告诉其中有多少个“l”:

count=$(echo "hello world" | tee /dev/tty | grep -o "l" | wc -l); echo "$count"

This will print:

这将打印:

hello world
3

回答by Ignacio Vazquez-Abrams

Send it to stderr.

将其发送到标准错误。

var="$(echo "hello" | tee /dev/stderr)"

Or copy stdout to a higher FD and send it there.

或者将 stdout 复制到更高的 FD 并将其发送到那里。

$ exec 10>&1
$ var="$(echo "hello" | tee /proc/self/fd/10)"
hello
$ echo "$var"
hello

回答by MatrixManAtYrService

A variation on Ignacio's answer:

伊格纳西奥回答的变体:

$ exec 9>&1                                                                                                              
$ var=$(echo "hello" | tee >(cat - >&9))   
hello                                                                              
$ echo $var
hello

Details here: https://stackoverflow.com/a/12451419/1054322

详情请见:https: //stackoverflow.com/a/12451419/1054322