How do you handle errors in shell scripts?

Answer

Key strategies: (1) Check $? after commands: if [ $? -ne 0 ]; then echo "Error"; exit 1; fi. (2) Use set -e at the top — exits the script on any command failure (use carefully; may exit prematurely). (3) set -u — treat unset variables as errors. (4) set -o pipefail — pipeline fails if any command in it fails (not just the last). (5) Combine: set -euo pipefail is a common "strict mode". (6) Use trap for cleanup on exit: trap 'rm -f /tmp/tempfile' EXIT. (7) Use || { echo "cmd failed"; exit 1; } pattern. Good error messages should include the line number ($LINENO) and context.