Search code examples
bashshellenvironment-variablesoutput-redirect

Redirect output to /dev/null only if VERBOSE is not set


How would you accomplish this?

if [[ -z $VERBOSE ]]; then
    REDIRECT=">/dev/null 2>/dev/null"
fi

echo "Installing Pip packages"  # Edited in for clarity
pip install requirements.txt $REDIRECT

echo "Installing other dependency"
<Install command goes here> $REDIRECT

Solution

  • You could redirect all output using exec:

    if [[ -z $VERBOSE ]]; then
        exec >/dev/null 2>&1
    fi
    
    pip install requirements.txt
    

    If you want to restore the output later on in the script you can duplicate the file descriptors:

    if [[ -z $VERBOSE ]]; then
        exec 3>&1
        exec 4>&2
        exec >/dev/null 2>&1
    fi
    
    # all the commands to redirect output for
    pip install requirements.txt
    # ...
    
    # restore output
    if [[ -z $VERBOSE ]]; then
        exec 1>&3
        exec 2>&4
    fi
    

    Another option is to open a file descriptor to either /dev/null or to duplicate descriptor 1:

    if [[ -z $VERBOSE ]]; then
        exec 3>/dev/null
    else
        exec 3>&1
    fi
    
    echo "Installing Pip packages"
    pip install requirements.txt >&3