conditional redirection in bash
For bash
, you can use the line:
exec &>/dev/null
This will direct all stdout
and stderr
to /dev/null
from that point on. It uses the non-argument version of exec
.
Normally, something like exec xyzzy
would replace the program in the current process with a new program but you can use this non-argument version to simply modify redirections while keeping the current program.
So, in your specific case, you could use something like:
tty -sif [[ $? -eq 1 ]] ; then exec &>/dev/nullfi
If you want the majority of output to be discarded but still want to output some stuff, you can create a new file handle to do that. Something like:
tty -sif [[ $? -eq 1 ]] ; then exec 3>&1 &>/dev/nullelse exec 3>&1fiecho Normal # won't see this.echo Failure >&3 # will see this.
I found another solution, but I feel it is clumsy, compared to paxdiablo's answer:
if tty -s; then REDIRECT=/dev/ttyelse REDIRECT=/dev/nullfiecho "Normal output" &> $REDIRECT
You can use a function:
function the_code { echo "is this visible?" # as many code lines as you want}if tty -s; then # or other condition the_codeelse the_code >& /dev/nullfi