这应该相对简单,但我以前从未碰到它,现在我正在摸不着头脑。
简单的脚本:
echo `tail /var/log/qmailcheck.log` >> $EMAIL
cat $EMAIL | mail -s "Daily server report from server.ca" email@here.com
(我知道我错过了tail
cmd周围的一组蜱,只是想让事情看起来正确)
问题在于,虽然我正在追踪的日志文件为每个条目都有一个新行,但是发送的电子邮件会将所有内容放在一行而不是:
Mon Feb 4 11:05:01 MST 2013-- Check Completed Successfully
Mon Feb 4 11:10:01 MST 2013-- Check Completed Successfully
Mon Feb 4 11:15:01 MST 2013-- Check Completed Successfully
Mon Feb 4 11:20:01 MST 2013-- Check Completed Successfully
Mon Feb 4 11:25:01 MST 2013-- Check Completed Successfully
我明白了:
Mon Feb 4 11:05:01 MST 2013-- Check Completed Successfully Mon Feb 4 11:10:01 MST 2013-- Check Completed Successfully Mon Feb 4 11:15:01 MST 2013-- Check Completed Successfully Mon Feb 4 11:20:01 MST 2013-- Check Completed Successfully Mon Feb 4 11:25:01 MST 2013-- Check Completed Successfully
该脚本也是来自其他一些命令的回声,它们似乎也遇到了一行,我之前已经做过但从未遇到过问题,我错过了什么?
以下是整个脚本:
ERROR=/tmp/errorlog
RECIP=$(cat /root/bin/emailrec)
echo Hi, this email to inform you of any potential issues with the server.bla qmail mail server > /tmp/demail
grep pls /var/log/qmailcheck.log > /tmp/errorlog
if [ ! -s $ERROR ] ; then
echo There are no errors in the qmailcheck log file >> /tmp/demail
echo Here are the last 10 lines of the current qmailcheck log file: >> /tmp/demail
tail /var/log/qmailcheck.log >> /tmp/demail
else
echo The log file for the qmail check script contains the following errors: >> /tmp/demail
cat $ERROR >> /tmp/demail
echo You should have also received an email which will better explain the error >> /tmp/demail
echo Check the time of the error above to determine when the email was sent >> /tmp/demail
fi
MAIL=$(/var/qmail/bin/qmail-qstat | grep "queue:" | awk '{ print $4 }')
echo There are $MAIL messages in the mail queue >> /tmp/demail
echo File system usage is currently at `df -h |grep vzfs | awk '{ print $5}'` >> /tmp/demail
cat /tmp/demail | mail -s "Daily server report from server.bla" $RECIP
答案 0 :(得分:2)
当您不需要使用echo 和命令替换时,这就是您所获得的。
唯一的区别
echo `command args...`
和
command args
是新线被折叠(并且代码更难阅读)。只需使用
tail /var/log/qmailcheck.log | mail -s ....
(如果您想使用中间文件,那么您也可以在没有echo
或反引号的情况下使用它。
请注意,还有另一种命令替换方式:$(command...)
,它可以解决嵌套引用的问题,并且通常更具可读性。无论何时需要命令替换,都可以使用此样式而不是反引号。
答案 1 :(得分:1)
变化:
echo `tail /var/log/qmailcheck.log` >> $EMAIL
为:
echo "`tail /var/log/qmailcheck.log`" >> $EMAIL
使用双引号包装命令替换可防止字符串拆分,这是将换行符转换为空格的地方。
但是,我建议使用Anton Kovalenko的解决方案。这里根本不需要使用echo
,只需将命令直接重定向到文件即可。