Shell 调试

没错, shell也可以调试.

看这样一个脚本:

  1. $ cat filesize.sh
  2. #!/bin/bash
  3. for filesize in $(ls -l . | grep "^-" | awk '{print $5}')
  4. do
  5. let totalsize=$totalsize+$filesize
  6. done
  7. echo "Total file size in current directory: $totalsize"

运行结果如下:

  1. $ ./filesize.sh
  2. Total file size in current directory: 652

添加调试信息:

  1. $ cat filesize.sh
  2. #!/bin/bash
  3. set -xv ## 注意这里!
  4. for filesize in $(ls -l . | grep "^-" | awk '{print $5}')
  5. do
  6. let totalsize=$totalsize+$filesize
  7. done
  8. echo "Total file size in current directory: $totalsize"

输出结果如下:

  1. $ ./fs.sh
  2. ++ ls -l .
  3. ++ grep '^-'
  4. ++ awk '{print $5}'
  5. + for filesize in '$(ls -l . | grep "^-" | awk '\''{print
  6. $5}'\'')'
  7. + let totalsize=+178
  8. + for filesize in '$(ls -l . | grep "^-" | awk '\''{print
  9. $5}'\'')'
  10. + let totalsize=178+285
  11. + for filesize in '$(ls -l . | grep "^-" | awk '\''{print
  12. $5}'\'')'
  13. + let totalsize=463+189
  14. + echo 'Total file size in current directory: 652'
  15. Total file size in current directory: 652

每次执行一条命令都会输出对应的命令和结果.

除了上面的方法, 还可以这样调试:

  1. $ bash -xv filesize.sh

直接在运行的时候调试.

很有用的我会乱说~