How can one handle errors and debug scripts that use shell_exec in PHP?

When using shell_exec in PHP, it's important to handle errors and debug any issues that may arise. One way to do this is by capturing the output and error messages from the shell command and checking for any errors. This can help identify the root cause of the problem and troubleshoot effectively.

$command = 'your_shell_command_here';
$output = shell_exec("$command 2>&1");

if ($output === null) {
    // Handle error or debug the issue
    echo "Error executing command: $command";
} else {
    // Process the output
    echo $output;
}