bashshelldev-null

Redirect to screen or /dev/null depending on flag


I'm trying to come up with a way script to pass a silent flag in a bash so that all output will be directed to /dev/null if it is present and to the screen if it is not.

An MWE of my script would be:

#!/bin/bash

# Check if silent flag is on.    
if [ $2 = "-s" ]; then
    echo "Silent mode."
    # Non-working line.
    out_var = "to screen"
else
    echo $1
    # Non-working line.
    out_var = "/dev/null"
fi

command1 > out_var

command2 > out_var

echo "End."

I call the script with two variables, the first one is irrelevant and the second one ($2) is the actual silent flag (-s):

./myscript.sh first_variable -s

Obviously the out_var lines don't work, but they give an idea of what I want: a way to direct the output of command1 and command2 to either the screen or to /dev/null depending on -s being present or not.

How could I do this?


Solution

  • You can use the naked exec command to redirect the current program without starting a new one.

    Hence, a -s flag could be processed with something like:

    if [[ "$1" == "-s" ]] ; then
        exec >/dev/null 2>&1
    fi
    

    The following complete script shows how to do it:

    #!/bin/bash
    
    echo XYZZY
    
    if [[ "$1" == "-s" ]] ; then
        exec >/dev/null 2>&1
    fi
    
    echo PLUGH
    

    If you run it with -s, you get XYZZY but no PLUGH output (well, technically, you do get PLUGH output but it's sent to the /dev/null bit bucket).

    If you run it without -s, you get both lines.

    The before and after echo statements show that exec is acting as described, simply changing redirection for the current program rather than attempting to re-execute it.


    As an aside, I've assumed you meant "to screen" to be "to the current standard output", which may or may not be the actual terminal device (for example if it's already been redirected to somewhere else). If you do want the actual terminal device, it can still be done (using /dev/tty for example) but that would be an unusual requirement.