Debugging

If testing reveals a problem the next step is debugging.

  1. Isolate

    Isolate the problem area by commenting out sections of code

    if [[ -d $dir_name ]]; then
        if cd $dir_name; then
            rm *
        else
            echo "cannot cd to '$dir_name'" >&2
            exit 1
        fi
    # else
    #    echo "no such directory: '$dir_name'" >&2
    #    exit 1
    fi
    
  2. Tracing

    Tracing by placing informative messages in the script

    echo "preparing to delete files" >&2
    if [[ -d $dir_name ]]; then
        if cd $dir_name; then
    echo "deleting files" >&2
            rm *
        else
            echo "cannot cd to '$dir_name'" >&2
            exit 1
        fi
    else
        echo "no such directory: '$dir_name'" >&2
        exit 1
    fi
    echo "file deletion complete" >&2
    

    Send messages to standard error to separate them from normal output. Don’t indent so easier to find when time to remove.

    Implement tracing by the -x options and the set command with the -x option.

    #!/bin/bash -x
    # trouble: script to demonstrate common errors
    number=1
    if [ $number = 1 ]; then
        echo "Number is equal to 1."
    else
        echo "Number is not equal to 1."
    fi
    

    example

    [me@linuxbox ~]$ trouble
    + number=1
    + '[' 1 = 1 ']'
    + echo 'Number is equal to 1.'
    Number is equal to 1.
    

    The + is the default char for trace output, contained in the PS4 shell variable.

    • You can change the PS4 variable to print line numbers

      [me@linuxbox ~]$ export PS4='$LINENO + '
      [me@linuxbox ~]$ trouble
      5 + number=1
      7 + '[' 1 = 1 ']'
      8 + echo 'Number is equal to 1.'
      Number is equal to 1.
      
    • To trace a section of the script, use set -x set +x

      #!/bin/bash
      
      # trouble: script to demonstrate common errors
      number=1
      
      set -x # Turn on tracing
      if [ $number = 1 ]; then
          echo "Number is equal to 1."
      else
          echo "Number is not equal to 1."
      fi
      set +x # Turn off tracing
      
  3. Examine values during execution

    Echo variables to see internal workings during execution

    echo "number=$number" # DEBUG
    set -x # Turn on tracing
    if [ $number = 1 ]; then
        echo "Number is equal to 1."
    else
        echo "Number is not equal to 1."
    fi
    set +x # Turn off tracing