在命令行执行脚本时,使用bash -x
后接脚本名,可以进入调试模式执行脚本。
bash +x
可以关闭调试模式,一般不会使用,因为脚本执行完毕后就退出调试模式了。
set -x
set -x
写在脚本中进入调试模式
在命令行直接使用 set -x 其实是开启了一个子shell
在这个子shell中执行的命令都会以调试模式输出,Ctrl-D 可以退出这个子shell回到原来的shell
或者在子shell中使用 set +x 也会退出这个子shell,即退出调试模式
进入调试模式后,bash脚本中的语句会被打印(前面以+ 开头),之后输出执行结果。
set +x
set +x
写在脚本中退出调试模式,之后的语句不再调试执行。
但是 set +x 这个语句本身会以调试模式打印出来,即:+ set +x
#!/bin/bash
debug_mode=true
echo "Before debug mode"
if [ "$debug_mode" = true ]; then
set -x
echo "This is a test command 1."
echo "This is a test command 2."
set +x
fi
echo "After debug mode"
Before debug mode
+ echo This is a test command 1.
This is a test command 1.
+ echo This is a test command 2.
This is a test command 2.
+ set +x
After debug mode
小技巧
如果不想打印 + set +x
,但是又想有范围限制地使用调试模式,可以使用子shell的方式,既可以省略 set +x 语句,还能有效控制调试范围,子shell执行完毕即结束调试,不会影响父shell。
#!/bin/bash
echo "Before debug mode"
(
set -x
echo "Inside debug mode"
)
echo "After debug mode"
配合标志变量使用更好
标志变量可读性更好,作为“开关”也能更方便高效的开启关闭调试模式,尤其是在需要频繁进入退出调试模式的场景下,复用调试模式代码,并改动标志变量即可方便地使用调试模式。
#!/bin/bash
debug_mode=true
echo "Before debug mode"
if [ "$debug_mode" = true ]; then
(
set -x
echo "Inside debug mode"
)
fi
echo "After debug mode"