debug_function_enter / debug_function_return

Function description

The debug_function_enter and debug_function_return functions may be used to selectively send debugging messages to stderr and / or the system event log indicating that a function has been entered or returned from. An indent value is also maintained, by incrementing on function enter and decrementing on function return, to aid visual parsing of the debugging output.

Function parameters

debug_function_enter

$1 - The name of the function. $2+ - The (optional) calling parameters, usually inserted using ${@} or similar, as shown in the example below.

debug_function_return

$1 - The (optional) return value.

Global variables

$DEBUG - If this global variable is set then output will be sent to stderr.

$LOGGING - If this global variable is set then output will be sent to the system event log.

Example use

Listing 1
  1. #! /bin/bash
  2.  
  3. # We rely on some functions from hacking-bash.sh
  4. [[ -r ${HACKING_BASH_LIB_PATH:=/usr/lib/hacking-bash.sh} ]] && \
  5.     source ${HACKING_BASH_LIB_PATH} || \
  6.     { echo "Unable to find ${HACKING_BASH_LIB_PATH}"; exit 1; }
  7.  
  8. # Simple recursive function to calculate a factorial
  9. function factorial
  10. {
  11.     debug_function_enter factorial ${@}
  12.    
  13.     if (( $1 == 0 )); then
  14.         debug_echo "calculated 1"
  15.         echo "1"
  16.     else
  17.         RETVAL=$(( ${1} * $(factorial $(( ${1} - 1 )) ) ))
  18.         debug_echo "calculated ${1} * factorial $(( ${1} - 1 )) = ${RETVAL}"
  19.         echo ${RETVAL}
  20.     fi
  21.    
  22.     debug_function_return
  23. }
  24.  
  25. # Set the DEBUG flag, we want output to the terminal
  26. DEBUG="true"
  27.  
  28. # Use the factorial function
  29. echo "The factorial of ${1} is $(factorial ${1})"
Example code demonstrating the debug_function_enter and debug_function_return functions
max@lisa ./debug_function_enter_return.sh 5
debug: function factorial 5
debug: {
debug:    function factorial 4
debug:    {
debug:        function factorial 3
debug:        {
debug:            function factorial 2
debug:            {
debug:                function factorial 1
debug:                {
debug:                    function factorial 0
debug:                    {
debug:                        calculated 1
debug:                    } 
debug:                    calculated 1 * factorial 0 = 1
debug:                } 
debug:                calculated 2 * factorial 1 = 2
debug:            } 
debug:            calculated 3 * factorial 2 = 6
debug:        } 
debug:        calculated 4 * factorial 3 = 24
debug:    } 
debug:    calculated 5 * factorial 4 = 120
debug: } 
The factorial of 5 is 120