How to silence output in a Bash script?

Viewed 258417

I have a program that outputs to stdout and would like to silence that output in a Bash script while piping to a file.

For example, running the program will output:

% myprogram
% WELCOME TO MY PROGRAM
% Done.

I want the following script to not output anything to the terminal:

#!/bin/bash
myprogram > sample.s
9 Answers

If it outputs to stderr as well you'll want to silence that. You can do that by redirecting file descriptor 2:

# Send stdout to out.log, stderr to err.log
myprogram > out.log 2> err.log

# Send both stdout and stderr to out.log
myprogram &> out.log      # New bash syntax
myprogram > out.log 2>&1  # Older sh syntax

# Log output, hide errors.
myprogram > out.log 2> /dev/null

Redirect stderr to stdout

This will redirect the stderr (which is descriptor 2) to the file descriptor 1 which is the the stdout.

2>&1

Redirect stdout to File

Now when perform this you are redirecting the stdout to the file sample.s

myprogram > sample.s

Redirect stderr and stdout to File

Combining the two commands will result in redirecting both stderr and stdout to sample.s

myprogram > sample.s 2>&1

Redirect stderr and stdout to /dev/null

Redirect to /dev/null if you want to completely silent your application.

myprogram >/dev/null 2>&1

Useful variations:


  • Get only the STDERR in a file, while hiding any STDOUT even if the program to hide isn't existing at all. (does not ever hang):

    stty -echo && ./programMightNotExist 2> errors.log && stty echo
    

  • Detach completely and silence everything, even killing the parent script won't abort ./prog (Does behave just like nohup):

    ./prog </dev/null >/dev/null 2>&1 &
    

  • nohup can be used as well to fully detach, as follow:

    nohup ./prog &
    

    A log file nohup.out will be created aside of the script, use tail -f nohup.out to read it.

Note: This answer is related to the question "How to turn off echo while executing a shell script Linux" which was in turn marked as duplicated to this one.

To actually turn off the echo the command is:

stty -echo

(this is, for instance; when you want to enter a password and you don't want it to be readable. Remember to turn echo on at the end of your script, otherwise the person that runs your script won't see what he/she types in from then on. To turn echo on run:

stty echo

For output only on error:

so [command]

Logo

Related