如果脚本失败,如何发送带有日志输出的电子邮件

如果脚本失败,如何发送带有日志输出的电子邮件

我编写了以下脚本模板,以使用 LFTP 将远程文件镜像到客户端的本地文件夹。如果镜像失败,我希望它发送一封电子邮件,其中包含记录的输出(但不是实际的日志文件,因为它可能相当长)。按原样,它只会显示退出状态 1。发送输出的最佳方式是什么?

#! /bin/bash

# Client info
client=example
data=/home/clients/$client/data
log=/home/clients/$client/log

# Create directories
mkdir -p $data $log

# LFTP settings
protocol="sftp://"
host="ftp.example.com"
user="example"
pass='123abc'
remote=/Outbound
command="mirror --verbose --continue $remote $data"

# Output to log
exec 3>&1 4>&2
trap 'exec 2>&4 1>&3' 0 1 2 3
exec 1>>$log/$client.log 2>&1

# Begin import | Recursively mirror remote to data
timestamp="$(date +"%m-%d-%Y@%T")"
echo "*** Time is $timestamp ***"
echo "Starting $client import."   
lftp -u $user,$pass $protocol$host <<EOF
set net:timeout 5
set net:max-retries 2
set net:reconnect-interval-base 5
$command
bye                                                     
EOF

#Store import exit status
import_exit_status=$?

# Send notification if feed import fails
if [ $import_exit_status -ne 0 ]; then
  /usr/sbin/sendmail "[email protected]" <<EOF
subject:$client Import Failed
from:notifications@host
Import failed with following reason(s):
$import_exit_status
EOF
else
  echo "Import complete."
  echo ""
fi

exit 0

相关内容