To debug a bash script you have several options, and some of these are even more effective than redirecting stdout/stderr.
You could add to your ~/.bash_profile
(creating a trace only for specific parts of your script) with
set -x # activate debugging from here
<commands>
set +x # stop debugging from here
Also, set -v
prints shell input lines as they are read, and set +v
deactivates this.
With this alone you will likely catch the problem.
Redirect trace
Use Bash Variable BASH_XTRACEFD
If set to an integer corresponding to a valid file descriptor, Bash will write the trace output generated when ‘set -x’ is enabled to that file descriptor. This allows tracing output to be separated from diagnostic and error messages. The file descriptor is closed when BASH_XTRACEFD is unset or assigned a new value. Unsetting BASH_XTRACEFD or assigning it the empty string causes the trace output to be sent to the standard error. Note that setting BASH_XTRACEFD to 2 (the standard error file descriptor) and then unsetting it will result in the standard error being closed.
So you would use
exec 5> ~/bash_profile_ouput.txt
BASH_XTRACEFD="5"
<commands>
unset BASH_XTRACEFD
Print line numbers
Use Bash Variable LINENO
(and BASH_LINENO
, BASH_SOURCE
and/or FUNCNAME
in more elaborate cases)
echo "Executing ${LINENO}"
<commands>
Redirect stdout/stderr
Combine command exec
with redirection, and possibly tee
.
See answers here, which also include other methods/"tricks" than using exec
.
Related:
- https://stackoverflow.com/questions/44249890/pipe-bash-stdout-only-in-debug-mode
- https://unix.stackexchange.com/questions/334382/find-out-what-scripts-are-being-run-by-bash-on-startup
- https://unix.stackexchange.com/questions/155551/how-to-debug-a-bash-script