Problem Statement
What techniques and tools can you use to debug shell scripts? Explain various debugging approaches.
Explanation
Set -x enables debug mode printing each command before execution with expanded variables: set -x at script start or bash -x script.sh runs entire script in debug. Disable with set +x. Output prefixed with +. Helps trace execution flow and see actual values. Use PS4 variable to customize prefix: export PS4='+(${BASH_SOURCE}:${LINENO}): ${FUNCNAME[0]:+${FUNCNAME[0]}(): }' shows file, line, and function.
Set -v (verbose) prints script lines as read before execution, showing raw commands. Combine: set -xv shows both raw and expanded. Set -e exits on first error, set -u exits on undefined variables, set -o pipefail fails on pipeline errors. Together: set -euxo pipefail creates strict mode catching most errors.
Strategic echo statements: add echo "Reached checkpoint 1" at key points, echo "VAR=$VAR" shows variable values, echo "$(date): processing $FILE" adds timestamps. Redirect debug output to file: exec 5> debug.log; BASH_XTRACEFD=5; set -x sends trace to file descriptor 5 instead of stderr.
Validation and testing: check exit status: command; echo $? shows return code, test command availability: command -v cmd tests if command exists, validate variables: [ -z "$VAR" ] && { echo "Error: VAR empty"; exit 1; }, verify file operations: [ -f "$FILE" ] || { echo "File not found"; exit 1; }.
Shellcheck is lint tool for shell scripts finding bugs, deprecated syntax, and suggesting improvements: shellcheck script.sh. Install and run on all scripts. Explains errors with wiki links. Bash -n script.sh checks syntax without executing.
Interactive debugging: trap 'read -p "Paused at line $LINENO. Press enter to continue..."' DEBUG pauses at each line. Function for debugging: debug() { [ "$DEBUG" ] && echo "DEBUG: $*" >&2; }; DEBUG=1 for debug mode. Use logging functions categorizing messages by severity. Understanding debugging techniques quickly identifies and fixes script issues.
Practice Sets
This question appears in the following practice sets: