庆典 - 自动捕捉最后执行的命令的输出到一个变量 [英] bash - automatically capture output of last executed command into a variable

查看:105
本文介绍了庆典 - 自动捕捉最后执行的命令的输出到一个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够在随后的命令中使用的最后一个执行的命令的结果。例如,

I'd like to be able to use the result of the last executed command in a subsequent command. For example,

$ find . -name foo.txt
./home/user/some/directory/foo.txt

现在,让我们说,我希望能够在编辑器中打开文件,或删除,或做点别的吧,例如

Now let's say I want to be able to open the file in an editor, or delete it, or do something else with it, e.g.

mv <some-variable-that-contains-the-result> /some/new/location

我该怎么办呢?也许使用一些bash的变量?

How can I do it? Maybe using some bash variable?

更新:

要澄清,我不想手动分配的事情。我后是一样的东西内置在bash的变量,例如

To clarify, I don't want to assign things manually. What I'm after is something like built-in bash variables, e.g.

ls /tmp
cd $_

$ _ 持有previous命令的最后一个参数。我想类似的东西,但最后一个命令的输出。

$_ holds the last argument of the previous command. I want something similar, but with the output of the last command.

最后更新:

Seth的答案已经相当奏效。事情夫妇牢记:

Seth's answer has worked quite well. Couple of things to bear in mind:


  • 请不要忘了触摸的/ tmp / X 试图为第一次的解决方案时,

  • 结果只会被保存,如果最后一个命令的退出code成功

  • don't forget to touch /tmp/x when trying the solution for the very first time
  • the result will only be stored if last command's exit code was successful

推荐答案

这是一个真正哈克的解决方案,但它似乎主要是一些工作的时间。在测试过程中,我注意到有时在命令行上获得当<大骨节病> ^ C 并没有很好地工作,虽然我没有调整它有点表现得更好一点。

This is a really hacky solution, but it seems to mostly work some of the time. During testing, I noted it sometimes didn't work very well when getting a ^C on the command line, though I did tweak it a bit to behave a bit better.

这是黑客交互模式只砍了,我pretty信心,我不会把它推荐给任何人。背景命令有可能导致比平常还要少定义的行为。其他的答案是在编程结果得到一个更好的办法。

This hack is an interactive mode hack only, and I am pretty confident that I would not recommend it to anyone. Background commands are likely to cause even less defined behavior than normal. The other answers are a better way of programmatically getting at results.

话虽这么说,这里是解决方案:

That being said, here is the "solution":

PROMPT_COMMAND='LAST="`cat /tmp/x`"; exec >/dev/tty; exec > >(tee /tmp/x)'

设置此bash的环境变量并根据需要发出命令。 $ LAST 通常会有你正在寻找的输出:

Set this bash environmental variable and issues commands as desired. $LAST will usually have the output you are looking for:

startide seth> fortune
Courtship to marriage, as a very witty prologue to a very dull play.
                -- William Congreve
startide seth> echo "$LAST"
Courtship to marriage, as a very witty prologue to a very dull play.
                -- William Congreve

这篇关于庆典 - 自动捕捉最后执行的命令的输出到一个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆