Debugging a Bash Script

Enabling verbose Mode

~]$ bash -v demo.sh

Syntax Checking Using noexec Mode

~]$ bash -n demo.sh

Debugging Using xtrace Mode

~]$ bash -x demo.sh

Identifying Unset Variables

~]$ bash -u demo.sh

Debugging Specific Parts of the Script

#!/usr/bin/env bash

set -x
echo "Debugging"
set +x

echo "Script Ended"

Bash Special Variables

#!/usr/bin/env bash

# Debug output script filename, line number, function name
PS4='+ ${BASH_SOURCE}:${LINENO}:${FUNCNAME[0]:+${FUNCNAME[0]}()} '

Redirecting Only the Debug Output to a File

#!/usr/bin/env bash

exec 3> /tmp/debug.log # Open an unused file descriptor.
BASH_XTRACEFD=3 # Make `set -x` output to file descriptor instead of stderr.