调试和$-
当一调试选项被激活时,这个选项的字母就被添加到变量$-。如果使用了-v,字母v就被添加到$-中,可以用以下语句来检测:
case $-in *v*)echo"using the v parameter';;
*x*) echo "using the x parameter";;
set command
激活调试模式时,整个脚本都有效,但有时你只想调试某一部分,这时你需要用set command
example:
#!/bin/bash
set -x
if [ -z "$1" ]; then
echo "ERROR: insufficient args"
exit 1
fi
当你设置了set命令后,如不禁止,他会在后面的所有脚本语句中都有效
关闭调试
set +opt
example:
shultdown the above debug:
set +x
shultdown all debug(关闭所有的调试):
set -
只对某个函数进入调试
set -x debugfunction set +x
语法检查
在处理shell脚本时,最好是在执行它之前,进行语法检查,如果你运行过C语言就知道,第一步是编译,也就是语法检查。
有如下脚本,脚本名为dg
#!/bin/bash
YN=y
if [ $YN = "yes" ]
echo "yes"
fi
你可以像这样检查他的语法:
$/bin/bash -n ./dg
./s1: line 5: syntax error near unexpected token `fi'
./s1: line 5: ` fi'