bash 如何将所有终端输出(包括错误消息)从脚本传输到日志文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22171771/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to pipe all terminal output including error messages from script to a log file
提问by Requist
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:
但即使如此,错误消息并不总是记录在我的文件中,当通过 cron 执行脚本(使用管道)时,我收到来自 rsync 和脚本错误的邮件:
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?
如何在我的日志文件中包含这些错误消息?
回答by fredtantini
To redirect STDERR to STDOUT, you have to add 2>&1
at the end of each line
要将 STDERR 重定向到 STDOUT,您必须2>&1
在每行末尾添加
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…
如果您有多个文件描述符,只需将它们全部重定向到 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
编辑:当我不记得文件描述符如何工作时,我去http://www.tldp.org/LDP/abs/html/io-redirection.html