3

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?

Requist
  • 155
  • 1
  • 1
  • 6
  • 1
    Say `>> log.file 2>&1` instead of `>> log.file`. – devnull Mar 04 '14 at 12:18
  • 1
    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. – Axel Mar 04 '14 at 12:19
  • 3 responses in the same minute, that is what I call a quick response! Thanks – Requist Mar 04 '14 at 12:50
  • 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`. – chepner Mar 04 '14 at 14:46
  • 1
    See also `teelog` in how-do-i-get-both-stdout-and-stderr-to-go-to-the-terminal-and-a-log-file http://stackoverflow.com/questions/363223 – denis May 07 '14 at 16:07

1 Answers1

11

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

fredtantini
  • 15,966
  • 8
  • 49
  • 55
  • Like ever, finding is more of a problem then solving. Works perfectly, thanks, also for the site which was not in my favorites yet. – Requist Mar 04 '14 at 13:16