问题描述
我正在编写一个Bash脚本,我希望所有命令在发生时都得到回显.我知道我需要分别使用set -x
和set +x
来切换此行为().但是,它并没有回显所有内容,即I/O重定向.
I am writing a Bash script where I want all commands to be echoed as they occur. I know that I need to use set -x
and set +x
to toggle this behaviour off and on, respectively (SOF post here). However, it doesn't echo everything, namely, I/O redirects.
例如,假设我有一个非常简单的Bash脚本:
For example, let's say I have this very simple Bash script:
set -x
./command1 > output1
./command2 arg1 arg2 > output2
这将是输出
+ ./command1
+ ./command2 arg1 arg2
Bash没有将我的标准输出重定向到 output1 和 output2 .为什么是这样?我如何实现这种行为?也许我必须在脚本中设置一个shopt
选项?
Bash is not echoing my stdout redirect to output1 and output2. Why is this? How can I achieve this behaviour? Perhaps is there a shopt
option that I must set in the script?
注意::我还注意到管道将无法按预期打印.例如,如果我要使用以下命令:
NOTE: I also noticed that pipes will not print as expected. For example, if I were to use this command:
set -x
./command3 | tee output3
我将得到以下输出:
+ tee output3
+ ./command3
如何使命令完全按照编写命令的方式回显,而不是通过脚本对管道进行重新排序?
How do I make the commands be echoed exactly in the way they are written instead of having the pipe reordered by the script?
推荐答案
set -x
不可能.您唯一的选择是通过DEBUG
陷阱查看当前命令.
It isn't possible with set -x
. Your only option is to view the current command through a DEBUG
trap.
trap 'printf %s\\n "$BASH_COMMAND" >&2' DEBUG
这不会像set -x
那样显示精确的参数.合并它们应该可以给您提供完整的画面,尽管它有很多调试输出.
This won't show the precise arguments as set -x
will. Combining them should give you the full picture, though it's a lot of debug output.
这篇关于Bash set -x echo重定向以及命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!