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

646 views Asked by At

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
2

There are 2 answers

0
Ted Lyngmo On BEST ANSWER

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

1
Shawn On

exec without a command:

#!/usr/bin/env bash

if [[ ${VERBOSE:-0} -eq 0  ]]; then
   exec >/dev/null 2>/dev/null
fi

echo "Some text."

Example:

$ ./example.sh
$ VERBOSE=1 ./example.sh
Some text.

${name:-word} expands to word if the variable name is unset or set to an empty string. This way you can also have VERBOSE=0 to turn it off.