使用 Bash 自动将最后一个命令的输出捕获到变量中?
我希望能够在后续命令中使用上次执行命令的结果。例如,
$ find . -name foo.txt
./home/user/some/directory/foo.txt
现在假设我希望能够在编辑器中打开该文件,或者删除它,或者用它做其他事情,例如
mv <some-variable-that-contains-the-result> /some/new/location
我该怎么做?也许使用一些 bash 变量?
更新:
澄清一下,我不想手动分配事情。我想要的是类似内置 bash 变量的东西,例如
ls /tmp
cd $_
$_
保存上一个命令的最后一个参数。我想要类似的东西,但带有最后一个命令的输出。
最终更新:
赛斯的回答非常有效。需要记住的几件事:
- 第一次尝试该解决方案时,不要忘记触摸 /tmp/x ,
- 只有最后一个命令的退出代码成功时才会存储结果
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
How can I do it? Maybe using some bash variable?
Update:
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.
Final update:
Seth's answer has worked quite well. Couple of things to bear in mind:
- 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(22)
有不止一种方法可以做到这一点。一种方法是使用
v=$(command)
,它将命令的输出分配给v
。例如:您也可以使用反引号。
来自 Bash 初学者指南,
编辑:在问题中进行编辑后,似乎这不是OP正在寻找的东西。据我所知,没有像
$_
这样的特殊变量用于最后一个命令的输出。There are more than one ways to do this. One way is to use
v=$(command)
which will assign the output of command tov
. For example:And you can use backquotes too.
From Bash Beginners Guide,
EDIT: After the edit in the question, it seems that this is not the thing that the OP is looking for. As far as I know, there is no special variable like
$_
for the output of last command.这很容易。使用反引号:
然后您可以在将来随时使用它
It's quite easy. Use back-quotes:
And then you can use that any time in the future
我认为您也许能够破解一个解决方案,该解决方案涉及将 shell 设置为包含以下内容的脚本:
然后,如果您设置
$PROMPT_COMMAND
来输出分隔符,您可以编写一个辅助函数(可能称为_
) 可以获取该日志的最后一块,因此您可以像以下那样使用它:I think you might be able to hack out a solution that involves setting your shell to a script containing:
Then if you set
$PROMPT_COMMAND
to output a delimiter, you can write a helper function (maybe called_
) that gets you the last chunk of that log, so you can use it like:您可以在 bash 配置文件中设置以下别名:
然后,通过在任意命令后键入“s”,您可以将结果保存到 shell 变量“it”中。
所以示例用法是:
You could set up the following alias in your bash profile:
Then, by typing 's' after an arbitrary command you can save the result to a shell variable 'it'.
So example usage would be:
使用反引号捕获输出:
Capture the output with backticks:
我刚刚从这里的建议中提取了这个 bash 函数:
然后,你只需执行:
更新:匿名用户建议将
echo
替换为printf '%s\n'
的优点是它不会处理抓取文本中的-e
等选项。因此,如果您预计或遇到此类特殊情况,请考虑此建议。另一种选择是使用cat <<<$grab
代替。I just distilled this
bash
function from the suggestions here:Then, you just do:
Update: an anonymous user suggested to replace
echo
byprintf '%s\n'
which has the advantage that it doesn't process options like-e
in the grabbed text. So, if you expect or experience such peculiarities, consider this suggestion. Another option is to usecat <<<$grab
instead.通过说“我希望能够在后续命令中使用最后执行的命令的结果”,我假设 - 你的意思是任何命令的结果,而不仅仅是查找。
如果那就是case - xargs 就是您正在寻找的。
<代码>查找 . -名称 foo.txt -print0 | xargs -0 -I{} mv {} /some/new/location/{}
或者,如果您有兴趣先查看输出:
find . -name foo.txt -print0
!! | xargs -0 -I{} mv {} /some/new/location/{}
此命令处理多个文件,即使路径和/或文件名包含空格,它也能发挥作用。
请注意命令的 mv {} /some/new/location/{} 部分。该命令是针对先前命令打印的每一行构建和执行的。此处,先前命令打印的行被替换为 {}。
xargs 手册页摘录:
有关更多详细信息,请参阅手册页:
man xargs
By saying "I'd like to be able to use the result of the last executed command in a subsequent command", I assume - you mean the result of any command, not just find.
If thats the case - xargs is what you are looking for.
find . -name foo.txt -print0 | xargs -0 -I{} mv {} /some/new/location/{}
OR if you are interested to see the output first:
find . -name foo.txt -print0
!! | xargs -0 -I{} mv {} /some/new/location/{}
This command deals with multiple files and works like a charm even if the path and/or filename contains space(s).
Notice the mv {} /some/new/location/{} part of the command. This command is build and executed for each line printed by earlier command. Here the line printed by earlier command is replaced in place of {}.
Excerpt from man page of xargs:
For more detail see man page:
man xargs
我通常会按照这里其他人的建议去做......没有作业:
如果你愿意,你可以变得更奇特:
I usually do what the others here have suggested ... without the assignment:
You can get fancier if you like:
如果您想要的只是重新运行最后一个命令并获取输出,一个简单的 bash 变量就可以工作:
那么您可以在输出上运行命令:
这将生成一个新进程并重新运行您的命令,然后为您提供输出。听起来您真正想要的是用于命令输出的 bash 历史文件。这意味着您需要捕获 bash 发送到终端的输出。您可以编写一些内容来监视 /dev 或 /proc 所需的内容,但这很混乱。您还可以在您的术语和 bash 之间创建一个“特殊管道”,并在中间使用 tee 命令重定向到您的输出文件。
但这两种解决方案都有些古怪。我认为最好的办法是 terminator 这是一个带有输出日志记录的更现代的终端。只需检查日志文件中最后一个命令的结果即可。与上面类似的 bash 变量将使这变得更加简单。
If all you want is to rerun your last command and get the output, a simple bash variable would work:
So then you can run your command on the output with:
This will spawn a new process and rerun your command, then give you the output. It sounds like what you would really like would be a bash history file for command output. This means you will need to capture the output that bash sends to your terminal. You could write something to watch the /dev or /proc necessary, but that's messy. You could also just create a "special pipe" between your term and bash with a tee command in the middle which redirects to your output file.
But both of those are kind of hacky solutions. I think the best thing would be terminator which is a more modern terminal with output logging. Just check your log file for the results of the last command. A bash variable similar to the above would make this even simpler.
在执行命令并决定将结果存储在变量中之后,这是一种方法:
或者,如果您提前知道需要将结果存储在变量中,则可以使用反引号:
Here's one way to do it after you've executed your command and decided that you want to store the result in a variable:
Or if you know ahead of time that you'll want the result in a variable, you can use backticks:
作为现有答案的替代方案:如果您的文件名可以包含这样的空格,请使用
while
:正如我所写,只有当您必须在文件名中预期空格时,差异才有意义。
注意:唯一的内置内容不是关于输出,而是关于最后一个命令的状态。
As an alternative to the existing answers: Use
while
if your file names can contain blank spaces like this:As I wrote, the difference is only relevant if you have to expect blanks in the file names.
NB: the only built-in stuff is not about the output but about the status of the last command.
你可以使用!!:1。例子:
you can use !!:1. Example:
我有类似的需求,我想将上一个命令的输出用于下一个命令。很像一个| (管道)。
例如
类似 -
解决方案:
创建了这个自定义管道。非常简单,使用 xargs -
基本上不需要为 xargs 创建一个简写,它的工作方式就像魅力一样,而且非常方便。
我只是在 .bash_profile 文件中添加别名。
I had a similar need, in which I wanted to use the output of last command into the next one. Much like a | (pipe).
eg
to something like -
Solution :
Created this custom pipe. Really simple, using xargs -
Basically nothing by creating a short hand for xargs, it works like charm, and is really handy.
I just add the alias in .bash_profile file.
这可以使用文件描述符的魔力和lastpipe shell 选项来完成。
它必须使用脚本完成 - “lastpipe”选项在交互模式下不起作用。
这是我测试过的脚本:
我在这里所做的是:
设置 shell 选项
shopt -s lastpipe
。这是行不通的如果没有这个,您将丢失文件描述符。
确保我的 stderr 也被
2>&1
捕获将输出通过管道传输到函数中,以便可以使用 stdin 文件描述符
引用。
通过获取内容来设置变量
/proc/self/fd/0
文件描述符,即 stdin。我使用它来捕获脚本中的错误,因此如果命令出现问题,我可以停止处理脚本并立即退出。
这样我就可以添加
2>&1 |退出测试; [[ "${PIPESTATUS[0]}" == "0" ]] || error_msg
位于我想要检查的每个命令后面。现在您可以享受您的输出了!
It can be done using the magic of file descriptors and the
lastpipe
shell option.It has to be done with a script - the "lastpipe" option will not work in interactive mode.
Here's the script I've tested with:
What I'm doing here is:
setting the shell option
shopt -s lastpipe
. It will not workwithout this as you will lose the file descriptor.
making sure my stderr also gets captured with
2>&1
piping the output into a function so that the stdin file descriptor can be
referenced.
setting the variable by getting the contents of the
/proc/self/fd/0
file descriptor, which is stdin.I'm using this for capturing errors in a script so if there is a problem with a command I can stop processing the script and exit right away.
In this way I can add
2>&1 | exit_tests ; [[ "${PIPESTATUS[0]}" == "0" ]] || error_msg
behind every command I care to check on.Now you can enjoy your output!
严格来说,这不是 bash 解决方案,但您可以使用 sed 管道来获取先前命令输出的最后一行。
首先让我们看看文件夹“a”中有什么
然后,您的 ls 和 cd 示例将变成 sed & 因此,真正的魔力发生在
sed 中,您将任何命令的输出通过管道传输到 sed 中,然后 sed 打印最后一行,您可以将其用作带有反引号的参数。或者您也可以将其与 xargs 结合起来。 (shell 中的“man xargs”是你的朋友)
This is not strictly a bash solution but you can use piping with sed to get the last row of previous commands output.
First lets see what i have in folder "a"
Then, your example with ls and cd would turn to sed & piping into something like this:
So, the actual magic happens with sed, you pipe what ever output of what ever command into sed and sed prints the last row which you can use as parameter with back ticks. Or you can combine that to xargs also. ("man xargs" in shell is your friend)
shell 没有类似 perl 的特殊符号来存储最后一个命令的回显结果。
学习在 awk 中使用管道符号。
在上面的例子中你可以这样做:
The shell doesn't have perl-like special symbols that store the echo result of the last command.
Learn to use the pipe symbol with awk.
In the example above you could do:
这是另一种方式,尽管很脏。
is yet another way, albeit dirty.
我发现记住将命令的输出通过管道传输到特定文件有点烦人,我的解决方案是
.bash_profile
中的一个函数,它捕获文件中的输出并在需要时返回结果它。这个的优点是您不必重新运行整个命令(当使用
find
或其他可能很关键的长时间运行的命令时)很简单,将其粘贴到您的
中。 bash_profile
:脚本
用法
此时,我倾向于只添加
| catch
到我所有命令的末尾,因为这样做没有任何成本,而且它使我不必重新运行需要很长时间才能完成的命令。另外,如果您想在文本编辑器中打开文件输出,您可以执行以下操作:
I find remembering to pipe the output of my commands into a specific file to be a bit annoying, my solution is a function in my
.bash_profile
that catches the output in a file and returns the result when you need it.The advantage with this one is that you don't have to rerun the whole command (when using
find
or other long-running commands that can be critical)Simple enough, paste this in your
.bash_profile
:Script
Usage
At this point, I tend to just add
| catch
to the end of all of my commands, because there's no cost to doing it and it saves me having to rerun commands that take a long time to finish.Also, if you want to open the file output in a text editor you can do this:
我不知道有任何变量可以自动执行此操作。除了复制粘贴结果之外,要做一些事情,您可以重新运行您刚才所做的任何事情,例如,
其中
!!
是历史扩展,意味着“上一个命令”。如果您希望单个文件名中包含空格或其他字符,可能会妨碍正确的参数解析,请引用结果(
vim "$(!!)"
)。不加引号将允许同时打开多个文件,只要它们不包含空格或其他 shell 解析标记即可。I don't know of any variable that does this automatically. To do something aside from just copy-pasting the result, you can re-run whatever you just did, eg
Where
!!
is history expansion meaning 'the previous command'.If you expect there to be a single filename with spaces or other characters in it that might prevent proper argument parsing, quote the result (
vim "$(!!)"
). Leaving it unquoted will allow multiple files to be opened at once as long as they don't include spaces or other shell parsing tokens.这是一个非常hacky的解决方案,但它似乎在某些时候大部分有效。在测试过程中,我注意到有时在命令行上获取 ^C 时效果不太好,尽管我确实对其进行了一些调整以使其表现得更好一些。
这个黑客只是一个交互模式黑客,我非常有信心我不会向任何人推荐它。后台命令可能会导致比正常情况更不明确的行为。其他答案是通过编程获得结果的更好方法。
话虽如此,这里是“解决方案”:
设置此 bash 环境变量并根据需要发出命令。
$LAST
通常会包含您要查找的输出: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.
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":
Set this bash environmental variable and issues commands as desired.
$LAST
will usually have the output you are looking for:Bash 是一种丑陋的语言。是的,您可以将输出分配给变量
但最好希望您最难的find
只返回一个结果,并且该结果中没有任何“奇怪”字符,例如回车符或换行符,因为它们在分配给 Bash 变量时会被默默地修改。但在使用变量时最好小心正确地引用它!
最好直接对文件进行操作,例如使用
find
的-execdir
(查阅手册)。或者
Bash is kind of an ugly language. Yes, you can assign the output to variable
But better hope your hardest thatfind
only returned one result and that that result didn't have any "odd" characters in it, like carriage returns or line feeds, as they will be silently modified when assigned to a Bash variable.But better be careful to quote your variable correctly when using it!
It's better to act on the file directly, e.g. with
find
's-execdir
(consult the manual).or
免责声明:
在 tmux 中运行交互式 shell 时,你可以轻松访问当前显示在终端上的数据。让我们看一下一些有趣的命令:
是的,这现在为我们提供了很多可能性:)对于我来说,我设置了一个简单的别名:
alias L="tmux capture-pane ; tmux showb -b 0 | tail -n 3 | head -n 1"
现在每次我需要访问最后一行时,我只需使用$(L)
来获取它。这与程序使用的输出流(stdin 或 stderr)、打印方法(ncurses 等)和程序的退出代码无关 - 只需要显示数据。
Disclamers:
When running an interactive shell in tmux, you can easily access the data currently displayed on a terminal. Let's take a look at some interesting commands:
Yeah, this gives us a lot of possibilities now :) As for me, I set up a simple alias:
alias L="tmux capture-pane; tmux showb -b 0 | tail -n 3 | head -n 1"
and now every time I need to access the last line i simply use$(L)
to get it.This is independent of the output stream the program uses (be it stdin or stderr), the printing method (ncurses, etc.) and the program's exit code - the data just needs to be displayed.