3

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.

1 Answer 1

3

The problem is going to be escaping everything correctly. Why don't you try a slightly different approach like this:

CMD='mysqldump -u"$user" -p"$pass" -h"$host" "$dbase" > "$dbase.sql.dump"';
[ "-d" = "$1" ] && echo $CMD
eval $CMD

The trick is saving the command as a variable and then printing the variable only if you are debugging. This removes the need of writing it out twice and you can then eval the variable to execute the command it contains.

3
  • I really didnt want a different line that was executed; ie the debug line is the same line that the non-debugged line is. Also gonna make code pretty ugly if every line takes three lines: one to set the CMD, for the check if debug and echo, and the last to eval the CMD
    – johnnyB
    Commented Sep 24, 2013 at 0:15
  • @johnnyB personally I wrap that kind of thing in a function and just call run_or_echo($CMD) and it's the function that checks -d and decides whether to echo or run. That's actually one less line per command than your original script. Anyway, I'm pretty sure you can't do it the way you want because the > will have to be used when you run the command and escaped when you are echoing it and you can't put the whole thing in quotes cause bash won't recognize it as a command. I don't see any way around this, > is a bash special character and your script is being interpreted by bash.
    – terdon
    Commented Sep 24, 2013 at 0:25
  • I don't see a work-around... maybe I'll go back to set -x -v but the output is ugly
    – johnnyB
    Commented Oct 4, 2013 at 22:03

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .