rub*_*o77 10 bash debugging output
有时添加真的很方便
set -x
Run Code Online (Sandbox Code Playgroud)
到脚本顶部以在执行之前显示所有命令。
创建具有体面输出的脚本只有一个缺点:我不知道如何以这种方式将文本输出添加到脚本中。如果我使用
echo 'some comment'
Run Code Online (Sandbox Code Playgroud)
它会导致打印结果翻倍:
+ echo 'some comment'
some comment
Run Code Online (Sandbox Code Playgroud)
如果我使用#它根本不显示。
如何添加打印出来的注释echo?如果我使用set -x?
Mic*_*mer 13
一种hacky 方法是将您的评论写为无操作命令的参数。特别有用的可能是:null 实用程序:
set -x
: Some interesting notes on the following are ...
Run Code Online (Sandbox Code Playgroud)
结果是:
set -x
: Some interesting notes on the following are ...
Run Code Online (Sandbox Code Playgroud)
冒号命令什么都不做,接受你给它的任何参数,并且总是成功。您:在跟踪输出开始时会得到一个额外的值,但这对您的目的来说可能不是什么大问题。
如果你不喜欢:一个更讨厌的技巧,那就是使用假命令:
set -x
seq 1 1
Some comment &>/dev/null
true
Run Code Online (Sandbox Code Playgroud)
将输出:
+ : Some interesting notes on the following are...
Run Code Online (Sandbox Code Playgroud)
也就是说,Some comment当 shell 尝试运行它时,该行作为跟踪输出打印出来,但产生的错误消息被发送到/dev/null. 由于许多明显的原因,这很令人讨厌,但对于set -e.
请注意,在任何一种情况下,您的注释都由 shell 以普通方式解析,因此特别是如果您有任何特殊字符需要引用它们,并且因为它是跟踪输出,将显示引用。
不要使用“set -x”来打印调试信息,而是使用单独的调试函数:
#!/bin/bash
DEBUG=1
debug() {
if [ $DEBUG == 1 ]
then
echo "DEBUG:" $@
fi
}
debug "foo bar"
Run Code Online (Sandbox Code Playgroud)
运行脚本产生
temeraire:ul jenny$ ./testdebug.sh
DEBUG: foo bar
Run Code Online (Sandbox Code Playgroud)
如果您将分配更改为 read DEBUG=0,则不会打印出该行。