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

查看:30
本文介绍了使用 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:

  • 第一次尝试解决方案时不要忘记触摸/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天全站免登陆