我正在尝试为大型备份脚本制作一个可读的日志文件
在脚本中,我只需将命令的所有输出通过管道传输到一个大文件中,然后脚本就可以对该文件进行"清理"。例如:
echo "Error occurred" >> log.file
mount disk >> log.file
当执行脚本时,我会在控制台上显示我错过的警告和错误。
backup.script >> log.file
但即便如此,错误消息也不总是记录在我的文件中,当通过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]
当出现脚本错误时:
/data/scripts/backup.auto: line 320: syntax error near unexpected token `else'
如何在日志文件中包含这些错误消息?
要将STDERR重定向到STDOUT,必须在每行的末尾添加2>&1
echo "Error occurred" >> log.file 2>&1
mount disk >> log.file 2>&1
如果您有多个文件描述符,只需将它们全部重定向到stdout 3>&1…
编辑:当我不记得文件描述符是如何工作的时,我会转到http://www.tldp.org/LDP/abs/html/io-redirection.html