2.3.1 在整个 脚步上调试
当事情不依照你计划的运行,你需要知道到底是什么导致脚本失败。bash提供了拓展性的debug特性。最常用的方式是以-x选项启动脚本,脚本就会以调试模式运行。跟踪每个命令和参数,并且还能把他们打印在标准输出里。
这是commented-script1.sh脚本运行在调试模式。注意添加了的注释不会出现在脚本的标志输出里。
willy:~/scripts> bash -x script1.sh
+ clear
+ echo 'The script starts now.'
The script starts now.
+ echo 'Hi, willy!'
Hi, willy!
+ echo
+ echo 'I will now fetch you a list of connected users:'
I will now fetch you a list of connected users:
+ echo
+ w
4:50pm up 18 days, 6:49, 4 users, load average: 0.58, 0.62, 0.40
USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
root tty2 - Sat 2pm 5:36m 0.24s 0.05s -bash
willy :0 - Sat 2pm ? 0.00s ? -
willy pts/3 - Sat 2pm 43:13 36.82s 36.82s BitchX willy ir
willy pts/2 - Sat 2pm 43:13 0.13s 0.06s /usr/bin/screen
+ echo
+ echo 'I'\''m setting two variables now.'
I'm setting two variables now.
+ COLOUR=black
+ VALUE=9
+ echo 'This is a string: '
This is a string:
+ echo 'And this is a number: '
And this is a number:
+ echo
+ echo 'I'\''m giving you back your prompt now.'
I'm giving you back your prompt now.
+ echo
2.3.2 在脚步的部分内容上调试
使用bash的内置命令set可以让你运用普通模式运行脚本的部分内容,并展示你觉得有错的调试信息。比如我们不确定w命令的作用,我们就可以使用set命令包围它。
set -x # activate debugging from here
w
set +x # stop debugging from here
输出就会这样
willy: ~/scripts> script1.sh
The script starts now.
Hi, willy!
I will now fetch you a list of connected users:
+ w
5:00pm up 18 days, 7:00, 4 users, load average: 0.79, 0.39, 0.33
USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
root tty2 - Sat 2pm 5:47m 0.24s 0.05s -bash
willy :0 - Sat 2pm ? 0.00s ? -
willy pts/3 - Sat 2pm 54:02 36.88s 36.88s BitchX willyke
willy pts/2 - Sat 2pm 54:02 0.13s 0.06s /usr/bin/screen
+ set +x
I'm setting two variables now.
This is a string:
And this is a number:
I'm giving you back your prompt now.
willy: ~/scripts>
你可以多次切换debug模式。
以下的表格展示了bash的选项。
Table 2-1. 调试选项
短命令 | 长命令 | Result |
---|---|---|
set -f | set -o noglob | 禁止带扩展名的路径 |
set -v | set -o verbose | 打印sheel的输入行 |
set -x | set -o xtrace | 在执行命令前打印命令 |
举个例子吧
willy:~/scripts> set -v
willy:~/scripts> ls
ls
commented-scripts.sh script1.sh
willy:~/scripts> set +v
set +v
willy:~/scripts> ls *
commented-scripts.sh script1.sh
willy:~/scripts> set -f
willy:~/scripts> ls *
ls: *: No such file or directory
willy:~/scripts> touch *
willy:~/scripts> ls
* commented-scripts.sh script1.sh
willy:~/scripts> rm *
willy:~/scripts> ls
commented-scripts.sh script1.sh
这些模式 可以在脚本里声明,只需要在第一行shell选项里声明。
#!/bin/bash -xv
一旦你发现你脚本有bug的部分,你可以添加echo语法来调试。
echo "debug message: now attempting to start w command"; w
echo也可以用来打印变量
echo "Variable VARNAME is now set to $VARNAME."