Bash命令的输出存储在任何寄存器中吗?例如,类似于$?捕获输出而不是退出状态。
我可以将输出赋值给一个变量:
output=$(command)
但那更多的是打字……
Bash命令的输出存储在任何寄存器中吗?例如,类似于$?捕获输出而不是退出状态。
我可以将输出赋值给一个变量:
output=$(command)
但那更多的是打字……
当前回答
我认为使用脚本命令可能会有帮助。类似的,
脚本-c bash -qf fifo_pid . sh 在解析后使用bash特性进行设置。
其他回答
答案是否定的。Bash不向内存中的任何参数或块分配任何输出。此外,您只能通过允许的接口操作来访问Bash。Bash的私人数据是无法访问的,除非你黑进去。
一种方法是使用DEBUG陷阱:
f() { bash -c "$BASH_COMMAND" >& /tmp/out.log; }
trap 'f' DEBUG
现在,最近执行的命令的stdout和stderr将在/tmp/out.log中可用
唯一的缺点是它将执行两次命令:一次将输出和错误重定向到/tmp/out.log,一次正常执行。也许也有一些方法可以防止这种行为。
受到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中,并且该命令不会被调用两次。
非常简单的解决方案
我已经用了很多年了。
脚本(添加到您的.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