What is the best way to conditionally do a redirection in Bash for testing and debugging purposes?
In my scripts I add a debug option to show what would have happened effectively doing a test run without any processing. If the debug option is on I want the DEBUG option to echo a script line with redirection effectively echoing the redirecton and not redirecting the echo. An example would probably explain this better:
In a script that would do a mysqldump using args passed to it, I would want the debug option to show the mysqldump command as it would have run if it wasn't for the -d option.
[ "-d" = "$1" ] && DEBUG=echo
$DEBUG mysqldump -u"$user" -p"$pass" -h"$host" "$dbase" > $dbase.sql.dump
So if I'm echoing cause DEBUG is "echo" I do NOT want to echo to "$dbase.sql.dump" I actually want to echo the ">" and the "$dbase" variable with the ".sql.dump" text. If the debug option isn't on I want to run the command as is.
The set -x
and set -v
options aren't really the answer here since debugging is really just a test output/dry-run option that the user can see and not really debugging the script to fix coding issues.