I have a simple script with a lot of output:

apt-get update && apt-get upgrade
} 2>&1

Starting it with ./script.sh >/dev/null 2>&1 silences it.

Can I silence the script from the inside?

  • 1
    I'm struggling to understand the question. – OrangeDog Dec 22 '15 at 20:43
  • @OrangeDog it's perfectly understandable; it could also phrased "How can I redirect my script's output from inside the script rather than on the command line?" – Wildcard Mar 4 '16 at 8:59
  • 1
    @Wildcard it has been edited since I made the comment. – OrangeDog Mar 4 '16 at 10:40

You can add the redirection in your script:

--EDIT-- after Jeff Schaller comment

# case 1: if you want to hide all message even errors
apt-get update && apt-get upgrade
} > /dev/null 2>&1

# case 2: if you want to hide all messages but errors
apt-get update && apt-get upgrade
} > /dev/null 
  • 2
    Note that 2>&1 > /dev/null assigns stderr to stdout, then assigns stdout to /dev/null -- the upshot will be that you'll see stderr messages. If the goal is to 'silence the script', you should rearrange the assignment to: > /dev/null 2>&1 – Jeff Schaller Dec 23 '15 at 13:28

This is what the bash built-in command exec is for (although it can perform other actions as well).

Excerpted from man bash on a CentOS 6.6 box:

   exec [-cl] [-a name] [command [arguments]]
          If command is not specified, any redirections take effect in the
          current shell, and the return status is 0.  If there is a 
          redirection error, the return status is 1.

So what you're looking for is exec >/dev/null 2>&1. You can use a getopts wrapper to only silence the script if the -q option is passed:


getopts :q opt
case $opt in
    exec >/dev/null 2>&1
shift "$((OPTIND-1))"

You don't need the getopts wrapper, but it might be nice. Either way, this is much cleaner than sticking your whole script in curly braces. You can also use exec to append output to a logfile:

exec 2>>/var/myscript_errors.log
exec >>/var/myscript_output.log

You get the idea. Very handy tool.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.