1

I have a bash script, but it gives me annoying output which I don't want to see. Of course I can hide it in that way:

./script.sh >/dev/null 2>&1

but I want to put the script in "rc.local" or "cron job", so it will be really bad if it received the output every 5 minutes for example, or on boot. It will be great if there is a way to tell the whole script to hide the output.

2
  • 1
    I'm not 100% sure what you're asking - if you never want to see the output, just redirect to /dev/null like you're doing. Perhaps provide a more concrete example of what you're trying to do? You might be interested in this question which discusses suppressing output only if the command succeeds. Commented Dec 16, 2015 at 0:39
  • 1
    Can't you just put ./script.sh >/dev/null 2>&1 in rc.local or crontab? Commented Dec 16, 2015 at 0:39

1 Answer 1

6

If you want to redirect all output to /dev/null within the script, that can be done like so (in this case, only performing the redirection if the environment variable DEBUG is not set):

#!/bin/bash
[[ $DEBUG ]] || exec >/dev/null 2>&1
# ...continue with execution here.

You could also check for whether your input is from a TTY to detect interactive use:

if [ -t 0 ]; then
  # being run by a human, be extra verbose
  PS4=':$LINENO+'
  set -x
else
  # being run by a daemon, be outright silent
  exec >/dev/null 2>&1
fi

See the bash-hackers page on the exec builtin.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.