Bash命令的输出存储在任何寄存器中吗?例如,类似于$?捕获输出而不是退出状态。

我可以将输出赋值给一个变量:

output=$(command)

但那更多的是打字……


当前回答

仅用于非交互式命令的演示:http://asciinema.org/a/395092

为了也支持交互式命令,您必须从util-linux中修改脚本二进制以忽略任何屏幕重画控制台代码,并从bashrc运行它以将登录会话的输出保存到一个文件中。

其他回答

如果你不想重新计算前一个命令,你可以创建一个宏,它扫描当前终端缓冲区,尝试猜测最后一个命令的-假设-输出,将其复制到剪贴板,最后将其输入到终端。

它可以用于返回单行输出的简单命令(在Ubuntu 18.04上使用gnome-terminal进行测试)。

安装以下工具:xdootool、xclip、ruby

在gnome-terminal选择首选项->快捷方式->全选并设置为Ctrl+shift+a。

创建以下ruby脚本:

cat >${HOME}/parse.rb <<EOF
#!/usr/bin/ruby
stdin = STDIN.read
d = stdin.split(/\n/)
e = d.reverse
f = e.drop_while { |item| item == "" }
g = f.drop_while { |item| item.start_with? "${USER}@" }
h = g[0] 
print h
EOF

在键盘设置中添加以下快捷键:

Bash -c '/bin/sleep 0.3;Xdotool键ctrl+shift+a;Xdotool键ctrl+shift+c;(xclip out | ${HOME}/parse. out)Rb) > /tmp/clipboard);(cat /tmp/clipboard | xclip -sel clip);Xdotool键ctrl+shift+v '

以上快捷方式:

将当前终端缓冲区复制到剪贴板 提取最后一个命令的输出(只有一行) 将其输入到当前终端

不确定你到底需要这个做什么,所以这个答案可能不相关。你总是可以保存命令的输出: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,它会在命令中创建一个变量并允许你对它进行操作。

答案是否定的。Bash不向内存中的任何参数或块分配任何输出。此外,您只能通过允许的接口操作来访问Bash。Bash的私人数据是无法访问的,除非你黑进去。

我有一个想法,但我没有时间立即尝试实施。

但如果你做了下面这样的事情:

$ MY_HISTORY_FILE = `get_temp_filename`
$ MY_HISTORY_FILE=$MY_HISTORY_FILE bash -i 2>&1 | tee $MY_HISTORY_FILE
$ some_command
$ cat $MY_HISTORY_FILE
$ # ^You'll want to filter that down in practice!

IO缓冲可能有问题。此外,文件可能会变得太大。人们必须想出解决这些问题的办法。

非常简单的解决方案

我已经用了很多年了。

脚本(添加到您的.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检索它。