#!/bin/bash
#
# Some tools to help you debug your scripts.
#
# 1. ShellCheck 
#
# https://www.shellcheck.net/
#
# Always use it for your scripts.
#
#
# 2. -x option
#
# You can start the (sub)shell with the -x option.
# It displays a '+' symbol and the command before executing it.
# Very useful to check the value of parameters and other expansions.
#
# Exercise: write a script with a syntax error (e.g., missing ';' in a
# while loop) or missing quotes around a variable expansion. 
# Run it as:
#
# $ bash -x script.sh
# 
# or add the -x in the shebang, or add the line 'set -x' at the point you
# want to start debugging (use 'set +x' to deactivate).
#
#
# 3. -e option
#
# Tells Bash to stop upon encoutering one error.
# Example: try the following script
#
# set -e
# ls /file/does/not/exist
# echo "hello, world"
#
#
# 4. -u option
#
# Break if a parameter that is about to be used is undefined.
# The script will produce an 'unbound variable' error and will exit.
#
#
# 5. bashdb
#
# The Bash Debugger project.
#
# https://bashdb.sourceforge.net
#
#
# 6. trace + DEBUG
#
# The DEBUG argument to trap causes a specified command to be executed
# after every command in a script.
# This can be used to trace (i.e., print) the value of variable.
# The $LINENO variable is useful to find in which line you are.

# Prints the value of $var after every command
trap 'echo "[TRACE] \$var = \"$var\""' DEBUG

var=42; line=$LINENO

echo "Variable \$var initialized to $var in line $line."
((var+=8)); line=$LINENO
echo "Added 8 to variable \$var in line $line."

exit 0

# Note: insert $LINENO in the trap echo command, i.e.,  [TRACE ($LINENO)],
# and see what happens.
