Search code examples
bashstdoutio-redirectionstderr

Redirect output for commands based on state of variable


I have many commands in a bash script that have >/dev/null 2>&1 used to redirect stdout and stderr to /dev/null.

Let us say I have a variable called echoOn, which can be either 0 or 1.

If echoOn is equal to 0, then I wish to keep the redirections on the commands in the script. If it is equal to 1, then I do not want the redirection in place, so the commands are able to output.

I do not wish to suppress the output of all commands but only specific ones within the script.

Is there a more abstract way for me to do this without manually adding if statements to every command in question?

I am open to having a function in which I pass the command and its arguments and replacing each command with a call to the aforementioned function and the command to be executed.


Solution

  • I'm not sure if I'm understanding your requiremens correctly, but how about:

    # put the lines below at the beginning of the script
    if (( echoOn == 0 )); then
        exec 3>/dev/null 2>&3
    else
        exec 3>&1
    fi
    
    # then execute your commands
    echo foo >&3    # a command which wants to switch the redirection
    echo warn >&2   # simulates an error
    echo bar        # a command which does not need the switch
    

    If echoOn is set to 0, only bar is displayed on the terminal.

    The problem is that you need to modify your code replacing all >/dev/null 2>&1 expressions with >&3.

    [Update]

    In order to controll both stdout and stderr on the specific command, please try the following:

    echoOn=0        # set to "1" to ebable stdout/stderr else set to "0"
    if (( echoOn == 0 )); then
        exec 3>/dev/null
        exec 4>/dev/null
    else
        exec 3>&1
        exec 4>&2
    fi
    
    echo foo 1>&3 2>&4          # a command which wants to switch the redirection
    (echo warn >&2) 1>&3 2>&4   # simulates an error
    echo bar                    # a command which does not need the switch
    (echo error >&2)            # simulates anerror
    

    Please put 1>&3 2>&4 to the commands you want to control its output