How do you debug a shell script?

Answer

Several techniques: (1) bash -x script.sh — enables xtrace mode, printing each command with a + prefix before executing it. (2) Add set -x inside the script to enable tracing at a specific point; set +x to disable. (3) set -v prints each line as it is read (before expansion). (4) bash -n script.sh — syntax-checks the script without executing (dry run). (5) Add echo "DEBUG: var=$var" statements. (6) Use set -euo pipefail to catch errors early. (7) PS4='${BASH_SOURCE}:${LINENO}+ ' makes xtrace output include file and line number. Tools: shellcheck (static analysis), bashdb (interactive debugger).