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?
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.
Sign up to join this communityI 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?
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
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:
#!/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.