Hack 86. How to Debug a shell script

by Ramesh

To debug a shell script use set –xv inside the shell script at the top.

Shell script with no debug command:

  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"

Output of Shell script with no debug command:

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

Shell script with Debug command inside:

Add set –xv inside the shell script now to debug the output as shown below.

  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"

Output of Shell script with Debug command inside:

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

Execute Shell script with debug option:

Instead of giving the set –xv inside the shell script, you can also provide that while executing the shell script as shown below.

  1. $ bash -xv filesize.sh