This is how I force debugging to turn on or off inside function blocks in bash scripts.
If debugging is on when the script starts, it is turned on inside function blocks. Each function block has a start and end message for easier tracing.
This is for runtime debugging. Best to redirect the output to a log file for analysis later, e.g.
bash -x ./runtime_bash_debugging>log 2>&1
-- or --
./runtime_bash_debugging>log 2>&1
Example output with debugging on at the start
$ bash -x ./runtime_bash_debugging.sh
+ run_me_first
+ FN_NAME=run_me_first
+ MSG='BEGINNING OF: run_me_first'
+ test '' = on
++ date
+ echo 'I run first, it'\''s Sat Oct 27 19:11:06 MDT 2018'
I run first, it's Sat Oct 27 19:11:06 MDT 2018
+ MSG='END OF: run_me_first'
+ test '' = on
+ run_me_second
+ FN_NAME=run_me_second
+ MSG='BEGINNING OF: run_me_second'
+ test '' = on
+ echo 'I run second, my PID is 5744'
I run second, my PID is 5744
+ MSG='END OF: run_me_second'
+ test '' = on
+ echo Goodbye
Goodbye
+ exit
Example output with debugging off at the start
$ ./runtime_bash_debugging.sh
I run first, it's Sat Oct 27 19:11:09 MDT 2018
I run second, the PID is 4784
Goodbye
THE SCRIPT
#!/bin/bash
# runtime bash debugging
fn_check_xtrace() {
XTRACE_BEGIN_STATE=`set -o|awk '$1=="xtrace"{print $2}'`
echo "${XTRACE_BEGIN_STATE}"
}
function run_me_first() {
FN_NAME="run_me_first"
MSG="BEGINNING OF: ${FN_NAME}"
if test "${XTRACE_BEGIN_STATE}" = "on"
then
set -x
fi
echo "I run first, it's `date`"
MSG="END OF: ${FN_NAME}"
if test "${XTRACE_BEGIN_STATE}" = "on"
then
set -x
fi
}
function run_me_second() {
FN_NAME="run_me_second"
MSG="BEGINNING OF: ${FN_NAME}"
if test "${XTRACE_BEGIN_STATE}" = "on"
then
set -x
fi
echo "I run second, the PID is $$"
MSG="END OF: ${FN_NAME}"
if test "${XTRACE_BEGIN_STATE}" = "on"
then
set -x
fi
}
run_me_first
run_me_second
echo "Goodbye"
exit