Bash命令的输出存储在任何寄存器中吗?例如,类似于$?捕获输出而不是退出状态。
我可以将输出赋值给一个变量:
output=$(command)
但那更多的是打字……
Bash命令的输出存储在任何寄存器中吗?例如,类似于$?捕获输出而不是退出状态。
我可以将输出赋值给一个变量:
output=$(command)
但那更多的是打字……
当前回答
你可以使用$(!!) 重新计算(而不是重新使用)上一个命令的输出。
的! !自行执行最后一个命令。
$ echo pierre
pierre
$ echo my name is $(!!)
echo my name is $(echo pierre)
my name is pierre
其他回答
答案是否定的。Bash不向内存中的任何参数或块分配任何输出。此外,您只能通过允许的接口操作来访问Bash。Bash的私人数据是无法访问的,除非你黑进去。
受到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中,并且该命令不会被调用两次。
如果你不想重新计算前一个命令,你可以创建一个宏,它扫描当前终端缓冲区,尝试猜测最后一个命令的-假设-输出,将其复制到剪贴板,最后将其输入到终端。
它可以用于返回单行输出的简单命令(在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检索它。