Bash脚本中使用调试模式

在命令行执行脚本时,使用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"
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值