How to pipe all terminal output including error messages from script to a log file
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
Requist
Updated on June 04, 2022Comments
-
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 about 10 yearsSay
>> log.file 2>&1
instead of>> log.file
. -
Axel about 10 yearsI 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
>>
and2>&1
is important btw. -
Requist about 10 years3 responses in the same minute, that is what I call a quick response! Thanks
-
chepner about 10 yearsNote 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 almost 10 yearsSee also
teelog
in how-do-i-get-both-stdout-and-stderr-to-go-to-the-terminal-and-a-log-file stackoverflow.com/questions/363223
-
-
Requist about 10 yearsLike ever, finding is more of a problem then solving. Works perfectly, thanks, also for the site which was not in my favorites yet.