简体   繁体   English

在 bash 中使用先前命令的输出

[英]Using output of previous commands in bash

In Mathematica, it is possible to reuse the output of the previous command by using %.在 Mathematica 中,可以通过使用 % 来重用前一个命令的输出。

Is something similar possible for bash (or some other shell)? bash(或其他一些shell)是否有类似的可能?

For example, I run a make which gives warnings, but I want to find all warnings.例如,我运行了一个发出警告的 make,但我想找到所有警告。 So, I type所以,我输入

make | grep "warning"

but I'm not able to see the output of the make then.但那时我看不到 make 的输出。

I would like to type something like this instead:我想输入这样的东西:

make
% | grep "warning"

Since the amount of output is indeterminate, it doesn't make sense for bash to store it for you for re-display.由于输出的数量是不确定的, bash为您存储它以供重新显示是没有意义的。 But there's an alternate solution to your problem:但是有一个替代解决方案可以解决您的问题:

The tee command allows you to duplicate an output stream to a file. tee命令允许您将输出流复制到文件中。 So if you're willing to use a file for temporary storage, you can do something like this:因此,如果您愿意将文件用作临时存储,则可以执行以下操作:

make | tee output.txt
grep "warning" output.txt

This solution avoids running make twice, which could be (a) expensive and (b) inconsistent: the second make may be doing less work than the first because some targets were already made the first time around.此解决方案避免运行make两次,这可能是 (a) 昂贵且 (b) 不一致:第二次 make 可能比第一个执行更少的工作,因为某些目标已经在第一次完成。

Note: I haven't tried this.注意:这个我没试过。 You may need to fiddle with joining the error and output streams, or such.您可能需要处理加入错误和输出流等问题。

You could do this:你可以这样做:

make
!! | grep "warning"

By using !!通过使用!! you tell it to repeat the last command in that spot, along with any other bash commands you want to add to it.你告诉它重复那个地方的最后一个命令,以及你想要添加的任何其他 bash 命令。

The downside is that if the command you are repeating takes a long time to execute, you'll have that much longer to wait unless you stored the output of the previous command to an output file first.不利的一面是,如果您要重复执行的命令需要很长时间才能执行,那么您将需要等待更长的时间,除非您先将上一个命令的输出存储到输出文件中。

交换stdoutstderr流以记录整个stderr流:

make 3>&2 2>&1 1>&3 3>&- | tee /dev/stderr > stderr.log

I'm not sure if the make command sends warnings to stderr but I suspect it does.我不确定make命令是否向 stderr 发送警告,但我怀疑它确实如此。 try this尝试这个

make 2&>1 |grep 'warning'

it will redirect stderr to stdout.它会将 stderr 重定向到 stdout。

Should also note that you can't grep anything that's not going to stdout.还应该注意,你不能 grep 任何不去标准输出的东西。

If you use tee to duplicate the output stream to /dev/stderr, there's no need for a temp file;如果您使用 tee 将输出流复制到 /dev/stderr,则不需要临时文件; plus, after that, you can filter the stdout stream with sed to create a make_warning.log file - all in one line of Unix shell pipes.另外,在那之后,您可以使用 sed 过滤 stdout 流以创建一个 make_warning.log 文件 - 所有这些都在一行 Unix shell 管道中。

make 2>&1 | tee /dev/stderr | \
   sed -E -n 's/(.*[Ww][Aa][Rr][Nn][Ii][Nn][Gg].*)/\1/p' > make_warning.log

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM