shell-调试手段

一. bash调试手段

1.1 echo/print

可以增加loglevel过滤一些log

_loglevel=2
 
DIE() {
    echo "Critical: $1" >&2
    exit 1
}
 
INFO() {
    [ $_loglevel -ge 2 ] && echo "INFO: $1" >&2
}
 
ERROR() {
    [ $_loglevel -ge 1 ] && echo "ERROR: $1" >&2
}

1.2 set -x

会在执行命令前,把调试信息打印出来

set -x
INFO "this is a info log"
ERROR "this is a error log"
set +x

效果如下:

+ INFO 'this is a info log'
+ '[' 2 -ge 2 ']'
+ echo -e '\033[32m INFO:\033[0m this is a info log'
 INFO: this is a info log
+ ERROR 'this is a error log'
+ '[' 2 -ge 1 ']'
+ echo -e '\033[33m ERR:\033[0m this is a error log'
 ERR: this is a error log
+ set +x

如果想全程打开 xtrace,可以在执行脚本的时候加 -x 参数

1.3 trap/bashdb

trap来指定各个sigspec应该执行的命令。
trap具体用法如下:

trap [-lp] [[arg] sigspec ...]

trap的内容包括以下五个方面:

内容 说明
signal kill可以发出的信号及0信号
EXIT EXIT 会在 shell 退出时执行指定的命令
RETURN 针对source和.每次引入都会触发
ERR 若当前 shell 中有命令执行返回非零值,则会执行与 ERR 相关联的命令
DEBUG 绑定后每一个命令执行之前,都会先执行 DEBUG 这个 trap

ERR和DEBUG默认只在当前的shell中有效,若想函数和子 shell 自动继承这些 trap,则可以设置 -T(DEBUG/RETURN) 和 -E(ERR)
例子:
shell退出时执行echo

#!/bin/bash
trap "echo this is a exit echo" EXIT
echo "this is a normal echo"

脚本中命令出错时,把命令打出来

#!/bin/bash
trap 'echo $BASH_COMMAND return err' ERR
echo this is a normal test
UnknownCmd

让脚本的命令单步执行

#!/bin/bash
trap '(read -p "[$0 : $LINENO] $BASH_COMMAND ?")' DEBUG
echo this is a test
i=0
while [ true ]
do
    echo $i
    ((i++))
done

常用的信号包括1,2,3,15
1----SIGHUP 挂起或父进程被杀死
2----SIGINT 来自键盘的中断<CTRL + C>
3----SIGQUIT 从键盘退出
15----SIGTERM 软终止
例子:在脚本捕捉到信号2后将会向用户提供一个选择,询问用户是否真的要退出。

#!/bin/sh
trap "my_exit" 1 2 3 15
my_exit() {
	echo -e "\nReceived interrupt..."
	echo "Do you wish to really exit ??"
	echo " Y: Yes"
	echo " N: No"
	echo -n "Your choice [Y..N] >"
	read ANS
	case $ANS in
		Y|y) exit 1;;
		N|n);;
	esac
}
echo -n "Enter your name: "
read NAME
echo -n "Enter your age: "
read AGE
posted @ 2016-08-15 21:28  zhangshihai1232  阅读(98)  评论(0)    收藏  举报