在 bash 脚本的 echo 命令中使用 sed

在 bash 脚本的 echo 命令中使用 sed

我想提取BackupPC中日志的最后一行,这样如果备份失败,我会通过电子邮件知道原因。我已使用该命令sed获取日志的最后一行。然而,我很难将其回显到屏幕上。它显示 FAILED 行,但不显示日志中的错误行。我该如何解决这个问题,和/或有更好的方法吗?

#!/bin/bash
# script to send simple email
# Email To ?
EMAIL="[email protected]"
# Email text/message
EMAILMESSAGE="/var/lib/backuppc/emailmessage.txt"
#Extract the last line of the log for error reporting
LOG_FILE="/var/lib/backuppc/log/LOG" 
#Grab the status variables
xferOK=$1
host=$2
type=$3
client=$4
hostIP=$5
share=$6
XferMethod=$7
sshPath=$8
cmdType=$9

# Check if backup succeeded or not.
if [[ $xferOK == 1 ]]; then
        STATUS="has been SUCCESSFUL"

# Email text/message
echo "$client backup $STATUS" > $EMAILMESSAGE
echo "------------------------------------------------------" >>$EMAILMESSAGE
echo "Type: $type" >>$EMAILMESSAGE
echo "Client: $client" >>$EMAILMESSAGE
echo "Host: $host" >>$EMAILMESSAGE
echo "Host IP: $hostIP" >>$EMAILMESSAGE
echo "Share: $share" >>$EMAILMESSAGE
echo "XferMethod: $XferMethod" >>$EMAILMESSAGE
echo "sshPath: $sshPath" >>$EMAILMESSAGE
echo "cmdType: $cmdType" >>$EMAILMESSAGE

/usr/sbin/sendmail "$EMAIL" < $EMAILMESSAGE


else
        STATUS="has FAILED"


#If it had failed, send out the error report
# Email text/message
echo "$client backup $STATUS" > $EMAILMESSAGE
echo "---------------------------------" >>$EMAILMESSAGE
echo "$LOG_FILE" | sed -n '$p' >>$EMAILMESSAGE

/usr/sbin/sendmail "$EMAIL" < $EMAILMESSAGE

我的电子邮件的输出。日志文件中没有任何行。

ukat2 backup has FAILED
---------------------------------

答案1

echo "$LOG_FILE" | sed -n '$p'不提取文件的最后一行$LOG_FILE,它提取发送到其标准输入的最后一行,即/var/lib/backuppc/log/LOG应出现在电子邮件中的日志文件名 ( )。

正确的语法是:

sed -n '$p' "$LOG_FILE"

或者,更好的是,因为显示最后 N 行是以下工作tail

tail -n 1 "$LOG_FILE"

相关内容