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

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

output=$(command)

但那更多的是打字……


当前回答

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

它可以用于返回单行输出的简单命令(在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,它会在命令中创建一个变量并允许你对它进行操作。

非常简单的解决方案

我已经用了很多年了。

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

你可以使用$(!!) 重新计算(而不是重新使用)上一个命令的输出。

的! !自行执行最后一个命令。

$ echo pierre
pierre
$ echo my name is $(!!)
echo my name is $(echo pierre)
my name is pierre

如果你在mac上,并且不介意将输出存储在剪贴板中,而不是写入到变量中,你可以使用pbcopy和pbpaste作为解决方案。

例如,与其这样做来查找一个文件并将其内容与另一个文件进行区分:

$ find app -name 'one.php' 
/var/bar/app/one.php

$ diff /var/bar/app/one.php /var/bar/two.php

你可以这样做:

$ find app -name 'one.php' | pbcopy
$ diff $(pbpaste) /var/bar/two.php

当你运行第一个命令时,字符串/var/bar/app/one.php就在剪贴板中。

顺便说一下,pbcopy和pbpaste中的pb代表粘贴板,是剪贴板的同义词。

我认为使用脚本命令可能会有帮助。类似的,

脚本-c bash -qf fifo_pid . sh 在解析后使用bash特性进行设置。