You can put a redirection on a list of commands:
{
command1
command2
} >/dev/null
If at some point in the script you don't want any output from subsequent commands, you can redirect the shell's output with the exec
builtin:
echo interesting
exec >/dev/null
echo boring
Note that this lasts until the end of the script, not just until the end of a function. This takes care of commands after the interesting one but not before.
There is a way to revert the effect of exec /dev/null
, by using file descriptor manipulations. I don't necessarily recommend it though, because it can be tricky to work out in practice. The idea is to relocate whatever is connected to the standard output to a different descriptor, then redirect standard output to a different file, and finally relocate the original standard output back to standard output.
{
exec 3>&1 # duplicate fd 3 to fd 1 (standard output)
exec >/dev/null # connect standard output to /dev/null
echo boring
exec 1>&3 # connect standard output back to what was saved in fd 3
echo interesting
exec >/dev/null # connect standard output to /dev/null again
echo more boring
} 3>/dev/null # The braced list must have its fd 3 connected somewhere,
# even though nothing will actually be written to it.