Bash命令的输出存储在任何寄存器中吗?例如,类似于$?捕获输出而不是退出状态。
我可以将输出赋值给一个变量:
output=$(command)
但那更多的是打字……
Bash命令的输出存储在任何寄存器中吗?例如,类似于$?捕获输出而不是退出状态。
我可以将输出赋值给一个变量:
output=$(command)
但那更多的是打字……
当前回答
一种方法是使用DEBUG陷阱:
f() { bash -c "$BASH_COMMAND" >& /tmp/out.log; }
trap 'f' DEBUG
现在,最近执行的命令的stdout和stderr将在/tmp/out.log中可用
唯一的缺点是它将执行两次命令:一次将输出和错误重定向到/tmp/out.log,一次正常执行。也许也有一些方法可以防止这种行为。
其他回答
仅用于非交互式命令的演示:http://asciinema.org/a/395092
为了也支持交互式命令,您必须从util-linux中修改脚本二进制以忽略任何屏幕重画控制台代码,并从bashrc运行它以将登录会话的输出保存到一个文件中。
受到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中,并且该命令不会被调用两次。
不确定你到底需要这个做什么,所以这个答案可能不相关。你总是可以保存命令的输出: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检索它。
我认为使用脚本命令可能会有帮助。类似的,
脚本-c bash -qf fifo_pid . sh 在解析后使用bash特性进行设置。