2.3.1 在整个 脚步上调试

当事情不依照你计划的运行,你需要知道到底是什么导致脚本失败。bash提供了拓展性的debug特性。最常用的方式是以-x选项启动脚本,脚本就会以调试模式运行。跟踪每个命令和参数,并且还能把他们打印在标准输出里。

这是commented-script1.sh脚本运行在调试模式。注意添加了的注释不会出现在脚本的标志输出里。

  1. willy:~/scripts> bash -x script1.sh
  2. + clear
  3. + echo 'The script starts now.'
  4. The script starts now.
  5. + echo 'Hi, willy!'
  6. Hi, willy!
  7. + echo
  8. + echo 'I will now fetch you a list of connected users:'
  9. I will now fetch you a list of connected users:
  10. + echo
  11. + w
  12. 4:50pm up 18 days, 6:49, 4 users, load average: 0.58, 0.62, 0.40
  13. USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
  14. root tty2 - Sat 2pm 5:36m 0.24s 0.05s -bash
  15. willy :0 - Sat 2pm ? 0.00s ? -
  16. willy pts/3 - Sat 2pm 43:13 36.82s 36.82s BitchX willy ir
  17. willy pts/2 - Sat 2pm 43:13 0.13s 0.06s /usr/bin/screen
  18. + echo
  19. + echo 'I'\''m setting two variables now.'
  20. I'm setting two variables now.
  21. + COLOUR=black
  22. + VALUE=9
  23. + echo 'This is a string: '
  24. This is a string:
  25. + echo 'And this is a number: '
  26. And this is a number:
  27. + echo
  28. + echo 'I'\''m giving you back your prompt now.'
  29. I'm giving you back your prompt now.
  30. + echo

bash有更完全的调试模式,在SourceForge。

2.3.2 在脚步的部分内容上调试

使用bash的内置命令set可以让你运用普通模式运行脚本的部分内容,并展示你觉得有错的调试信息。比如我们不确定w命令的作用,我们就可以使用set命令包围它。

  1. set -x # activate debugging from here
  2. w
  3. set +x # stop debugging from here

输出就会这样

  1. willy: ~/scripts> script1.sh
  2. The script starts now.
  3. Hi, willy!
  4. I will now fetch you a list of connected users:
  5. + w
  6. 5:00pm up 18 days, 7:00, 4 users, load average: 0.79, 0.39, 0.33
  7. USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
  8. root tty2 - Sat 2pm 5:47m 0.24s 0.05s -bash
  9. willy :0 - Sat 2pm ? 0.00s ? -
  10. willy pts/3 - Sat 2pm 54:02 36.88s 36.88s BitchX willyke
  11. willy pts/2 - Sat 2pm 54:02 0.13s 0.06s /usr/bin/screen
  12. + set +x
  13. I'm setting two variables now.
  14. This is a string:
  15. And this is a number:
  16. I'm giving you back your prompt now.
  17. willy: ~/scripts>

你可以多次切换debug模式。

以下的表格展示了bash的选项。

Table 2-1. 调试选项

短命令 长命令 Result
set -f set -o noglob 禁止带扩展名的路径
set -v set -o verbose 打印sheel的输入行
set -x set -o xtrace 在执行命令前打印命令

举个例子吧

  1. willy:~/scripts> set -v
  2. willy:~/scripts> ls
  3. ls
  4. commented-scripts.sh script1.sh
  5. willy:~/scripts> set +v
  6. set +v
  7. willy:~/scripts> ls *
  8. commented-scripts.sh script1.sh
  9. willy:~/scripts> set -f
  10. willy:~/scripts> ls *
  11. ls: *: No such file or directory
  12. willy:~/scripts> touch *
  13. willy:~/scripts> ls
  14. * commented-scripts.sh script1.sh
  15. willy:~/scripts> rm *
  16. willy:~/scripts> ls
  17. commented-scripts.sh script1.sh

这些模式 可以在脚本里声明,只需要在第一行shell选项里声明。

  1. #!/bin/bash -xv

一旦你发现你脚本有bug的部分,你可以添加echo语法来调试。

  1. echo "debug message: now attempting to start w command"; w

echo也可以用来打印变量

  1. echo "Variable VARNAME is now set to $VARNAME."