Bash – How to Use Output Redirection Dynamically

bashio-redirectionshell-script

I'm trying to add a debug option to a script of mine. Normally I want to hide any output, like warnings etc, so I put >/dev/null 2>&1 behind a lot of commands.

Now, when I want to debug my script, I would have to manually remove those, or put every command inside an if ... fi testing for a $DEBUG Variable.

I thought putting >/dev/null 2>&1 inside a Variable ($REDIR) and writing command arg1 $REDIR would do the trick. If I want to debug, I would only need to leave $REDIR empty.

But a short test on my shell showed me, that it won't work that way:

~$ echo "bla" >/dev/null 2>&1
~$ REDIR=>/dev/null 2>&1
~$ echo "bla" $REDIR
bla
~$

Using " or ' around >/dev/null 2>&1 didn't work either for obvious reasons.

So why does my idea not work here? Did I misunderstand something about putting commands etc. into Variables and calling them?

Best Answer

For such a purpose I usually define a function like run. This can correctly handle args with spaces and others in most cases.

#!/bin/bash

run() {
        if $DEBUG; then
                v=$(exec 2>&1 && set -x && set -- "$@")
                echo "#${v#*--}"
                "$@"
        else
                "$@" >/dev/null 2>&1
        fi
}

DEBUG=false
run echo "bla"

DEBUG=true
run echo "bla"
run printf "%s . %s . %s\n" bla "more bla" bla

Output:

$ bash debug.sh 
# echo bla
bla
# printf '%s . %s . %s\n' bla 'more bla' bla
bla . more bla . bla
Related Question