How to silence output in a Bash script?

后端 未结 9 2046
离开以前
离开以前 2020-11-29 17:15

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:<

相关标签:
9条回答
  • 2020-11-29 17:38

    For output only on error:

    so [command]

    0 讨论(0)
  • 2020-11-29 17:41

    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
    
    0 讨论(0)
  • 2020-11-29 17:50

    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

    0 讨论(0)
  • 2020-11-29 17:53

    All output:

    scriptname &>/dev/null
    

    Portable:

    scriptname >/dev/null 2>&1
    

    Portable:

    scriptname >/dev/null 2>/dev/null
    

    For newer bash (no portable):

    scriptname &>-
    
    0 讨论(0)
  • 2020-11-29 17:53

    Try with:

    myprogram &>/dev/null
    

    to get no output

    0 讨论(0)
  • 2020-11-29 17:56

    Useful in scripts:


    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 parent script), this alone was working:

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

    Detach completely and silence everything, even killing the parent script won't abort ./prog :

     ./prog </dev/null >/dev/null 2>&1 &
    
    0 讨论(0)
提交回复
热议问题