Bash命令的输出存储在任何寄存器中吗?例如,类似于$?捕获输出而不是退出状态。
我可以将输出赋值给一个变量:
output=$(command)
但那更多的是打字……
Bash命令的输出存储在任何寄存器中吗?例如,类似于$?捕获输出而不是退出状态。
我可以将输出赋值给一个变量:
output=$(command)
但那更多的是打字……
当前回答
非常简单的解决方案
我已经用了很多年了。
脚本(添加到您的.bashrc或.bash_profile)
# capture the output of a command so it can be retrieved with ret
cap () { tee /tmp/capture.out; }
# return the output of the most recent command that was captured by cap
ret () { cat /tmp/capture.out; }
使用
$ find . -name 'filename' | cap
/path/to/filename
$ ret
/path/to/filename
我倾向于在所有命令的末尾添加|。这样,当我发现我想对一个缓慢运行的命令的输出进行文本处理时,我总是可以用ret检索它。
其他回答
答案是否定的。Bash不向内存中的任何参数或块分配任何输出。此外,您只能通过允许的接口操作来访问Bash。Bash的私人数据是无法访问的,除非你黑进去。
仅用于非交互式命令的演示:http://asciinema.org/a/395092
为了也支持交互式命令,您必须从util-linux中修改脚本二进制以忽略任何屏幕重画控制台代码,并从bashrc运行它以将登录会话的输出保存到一个文件中。
就像konsolebox说的,你必须黑进bash本身。这里有一个很好的例子来说明如何实现这一点。stderred存储库(实际上是为stdout上色)给出了如何构建它的说明。
我尝试了一下:在.bashrc中定义一些新的文件描述符,比如
exec 41>/tmp/my_console_log
(数字是任意的),并相应地修改stderred.c,以便内容也被写入fd 41。它可以工作,但是包含大量的NUL字节,奇怪的格式,基本上是二进制数据,不可读。也许对C语言很了解的人可以尝试一下。
如果是这样,那么获取最后打印行的所有内容都是tail -n 1 [logfile]。
不确定你到底需要这个做什么,所以这个答案可能不相关。你总是可以保存命令的输出:netstat >> output.txt,但我不认为这是你想要的。
当然也有编程选项;你可以简单地让一个程序在命令运行后读取上面的文本文件,并将其与一个变量关联起来,在Ruby中,我选择的语言,你可以使用'反撇号'从命令输出中创建一个变量:
output = `ls` #(this is a comment) create variable out of command
if output.include? "Downloads" #if statement to see if command includes 'Downloads' folder
print "there appears to be a folder named downloads in this directory."
else
print "there is no directory called downloads in this file."
end
将其插入到.rb文件中并运行:ruby file。Rb,它会在命令中创建一个变量并允许你对它进行操作。
受到anubhava回答的启发,我认为这实际上是不可接受的,因为它将每个命令运行两次。
save_output() {
exec 1>&3
{ [ -f /tmp/current ] && mv /tmp/current /tmp/last; }
exec > >(tee /tmp/current)
}
exec 3>&1
trap save_output DEBUG
这样,最后一个命令的输出就在/tmp/last中,并且该命令不会被调用两次。