4

I have a simple script with a lot of output:

#!/bin/bash
{
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?

3
  • 1
    I'm struggling to understand the question. Commented Dec 22, 2015 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?" Commented Mar 4, 2016 at 8:59
  • 1
    @Wildcard it has been edited since I made the comment. Commented Mar 4, 2016 at 10:40

2 Answers 2

7

You can add the redirection in your script:

--EDIT-- after Jeff Schaller comment

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


#!/bin/bash
# case 2: if you want to hide all messages but errors
{
apt-get update && apt-get upgrade
} > /dev/null 
1
  • 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 Commented Dec 23, 2015 at 13:28
1

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:

#!/bin/bash

getopts :q opt
case $opt in
  q)
    exec >/dev/null 2>&1
    ;;
esac
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.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.