![如果脚本失败,如何发送带有日志输出的电子邮件](https://linux22.com/image/187236/%E5%A6%82%E6%9E%9C%E8%84%9A%E6%9C%AC%E5%A4%B1%E8%B4%A5%EF%BC%8C%E5%A6%82%E4%BD%95%E5%8F%91%E9%80%81%E5%B8%A6%E6%9C%89%E6%97%A5%E5%BF%97%E8%BE%93%E5%87%BA%E7%9A%84%E7%94%B5%E5%AD%90%E9%82%AE%E4%BB%B6.png)
我编写了以下脚本模板,以使用 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