How to pipe all terminal output including error messages from script to a log file

15,133

To redirect STDERR to STDOUT, you have to add 2>&1 at the end of each line

echo "Error occurred" >> log.file 2>&1
mount disk >> log.file 2>&1

If you have multiple file descriptor, just redirect all of them to stdout 3>&1…

Edit: when I don't remember how file descriptors work, I go to http://www.tldp.org/LDP/abs/html/io-redirection.html

Share:
15,133
Requist
Author by

Requist

Updated on June 04, 2022

Comments

  • Requist
    Requist almost 2 years

    I am trying to make a readable log file for a large backupscript.
    Within the script I simply pipe all output from the commands to a big file which then later can be "cleaned" by the script. For example:

    echo "Error occurred" >> log.file
    mount disk >> log.file
    

    The warnings and error I have missed I pipe at the console when executing the script.

    backup.script >> log.file
    

    But even than, error messages are not always logged in my file, when executing the script (with pipe) by cron I get mails from rsync and script errors:

    rsync: writefd_unbuffered failed to write 4 bytes to socket [sender]: Broken pipe (32)
    rsync: write failed on "/mnt/backup1/xxxxx": No space left on device (28)
    rsync error: error in file IO (code 11) at receiver.c(322) [receiver=3.0.9]
    rsync: connection unexpectedly closed (215 bytes received so far) [sender]
    rsync error: error in rsync protocol data stream (code 12) at io.c(605) [sender=3.0.9]
    

    and when a script error occurs:

    /data/scripts/backup.auto: line 320: syntax error near unexpected token `else'
    

    How can I include these error messages in my log file?

    • devnull
      devnull about 10 years
      Say >> log.file 2>&1 instead of >> log.file.
    • Axel
      Axel about 10 years
      I am in office, so I cannot try it (no linux here), but the reason is different file descriptors are used. devnull just gave the answer to this. The order of >> and 2>&1 is important btw.
    • Requist
      Requist about 10 years
      3 responses in the same minute, that is what I call a quick response! Thanks
    • chepner
      chepner about 10 years
      Note that you can clean your script up by grouping consecutive commands that write to the same file: echo foo >> log.file; echo bar >> log.file would become { echo foo; echo bar; } >> log.file.
    • denis
      denis almost 10 years
      See also teelog in how-do-i-get-both-stdout-and-stderr-to-go-to-the-terminal-an‌​d-a-log-file stackoverflow.com/questions/363223
  • Requist
    Requist about 10 years
    Like ever, finding is more of a problem then solving. Works perfectly, thanks, also for the site which was not in my favorites yet.