使用Bash自动将最后一个命令的输出捕获到变量中? [英] Automatically capture output of last command into a variable using Bash?

查看:148
本文介绍了使用Bash自动将最后一个命令的输出捕获到变量中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够在后续命令中使用最后执行的命令的结果.例如,

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 $_

$_保留上一个命令的最后一个参数.我想要类似的东西,但输出的是最后一条命令.

$_ 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:

  • 在初次尝试解决方案时不要忘记touch /tmp/x
  • 仅在上一个命令的退出代码成功后才存储结果

推荐答案

这是一个非常骇人听闻的解决方案,但在某些时候似乎可以正常工作.在测试过程中,我注意到在命令行上获取 ^ 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.

此hack仅是一种交互模式hack,我非常有信心不会将它推荐给任何人.后台命令可能导致比正常情况更少的定义行为.其他答案是通过编程获得结果的更好方法.

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

这篇关于使用Bash自动将最后一个命令的输出捕获到变量中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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