bash debugging

Updated: 03 May 2023

see https://tldp.org/LDP/Bash-Beginners-Guide/html/sect_02_03.html

Start subshell with -x option, which will run the entire script in debug mode. Traces of each command plus its arguments are printed to standard output after the commands have been expanded but before they are executed.

bash -x script1.sh

Debugging can be activated for a portion of the script

set -x			# activate debugging from here
call_my_func
set +x			# stop debugging from here

Other useful bash options

Short notation Long notation Result
set -v set -o verbose Prints shell input lines as they are read.
set -x set -o xtrace Print command traces before executing command.

Alternatively, these modes can be specified in the script itself, by adding the desired options to the first line shell declaration. Options can be combined, as is usually the case with UNIX commands

#!/bin/bash -xv

Examples of using echo for debugging

echo "debug message: now attempting to start w command"; w

echo "Variable VARNAME is now set to $VARNAME."

WordPress debugging

Updated: 28 March 2024

To enable debugging generally, add these lines to file wp-config.php just before /* That's all, stop editing! Happy publishing. */

// Turn debugging on
define('WP_DEBUG', true);

// Tell WordPress to log everything to /wp-content/debug.log
define('WP_DEBUG_LOG', true);

// Display errors and warnings on the frontend
define( 'WP_DEBUG_DISPLAY', true );
@ini_set( 'display_errors', 1 );

Write any message to /wp-content/debug.log

error_log('logging message here...');

Write a PHP variable to the error log with print_r

error_log(print_r($var, true));

Write a PHP variable to the error log with var_dump

function error_log_var_dump( $var ){
    ob_start();
    var_dump( $var );
    $cont = ob_get_contents();
    ob_end_clean();
    error_log( $cont );
}