Writing shell scripts can get tricky, so knowing how to log output and debug your scripts is 🔑.
Redirect standard output (stdout) and error (stderr) to log files:
# Redirect stdout to file
echo "Hello, log!" > output.log
# Redirect stderr to file
ls non_existent_file 2> error.log
# Redirect both stdout and stderr to the same file
command &> all_output.log
bash -x script.sh
— Run script with debug info showing commands as they execute.set -x
— Turn on debug mode inside the script.set +x
— Turn off debug mode.echo
or printf
to print variable values during execution.Simulate bash -x
, set -x
, set +x
to see commands traced during execution.
set -x
to turn ON debug mode and set +x
to turn it OFF inside your script.