linux - 如何在 shell 脚本中为失败的作业发送电子邮件

标签 linux bash shell email

我有一个 shell 脚本。我正在向该脚本传递文件中的参数。此文件包含表名

脚本运行良好。我能够对文件中的所有表执行命令。

shell 脚本

#!/bin/bash

[ $# -ne 1 ] && { echo "Usage : $0 input file "; exit 1; }
input_file=$1

TIMESTAMP=`date "+%Y-%m-%d"`
touch /home/$USER/logs/${TIMESTAMP}.success_log
touch /home/$USER/logs/${TIMESTAMP}.fail_log 
success_logs=/home/$USER/logs/${TIMESTAMP}.success_log
failed_logs=/home/$USER/logs/${TIMESTAMP}.fail_log

#Function to get the status of the job creation
function log_status
{
       status=$1
       message=$2
       if [ "$status" -ne 0 ]; then
                echo "`date +\"%Y-%m-%d %H:%M:%S\"` [ERROR] $message [Status] $status : failed" | tee -a "${failed_logs}"
                #echo "Please find the attached log file for more details"
                #exit 1
                else
                    echo "`date +\"%Y-%m-%d %H:%M:%S\"` [INFO] $message [Status] $status : success" | tee -a "${success_logs}"
                fi
}


while read table ;do 
  sqoop job --exec $table > /home/$USER/logging/"${table}_log" 2>&1
  g_STATUS=$?
  log_status $g_STATUS "Sqoop job ${table}"
  cp /home/$USER/logging/"${table}_log" /home/$USER/debug/`date "+%Y-%m-%d"`/logs/
done < ${input_file}

现在我想将失败的作业的电子邮件发送到我的电子邮件地址。

要求

1) Send email for each failed job i.e If `status log` has failed job for one particular table then I want email sent out saying job for that table has failed. 

2) Or Send out one email for all the jobs that have failed for one input file.

这是最好的方法。我希望 2nd 选项至少可以减少要处理的电子邮件数量。

但如果我知道这两种方法就更好了

edited function log_status

#Function to get the status of the job creation
function log_status
{
       status=$1
       message=$2
       if [ "$status" -ne 0 ]; then
                echo "`date +\"%Y-%m-%d %H:%M:%S\"` [ERROR] $message [Status] $status : failed" | tee -a "${failed_logs}"
                mail -a mail.txt -s "This is the failed job log" user@example.com < /home/$USER/logs/${TIMESTAMP}.fail_log
                #exit 1
                else
                    echo "`date +\"%Y-%m-%d %H:%M:%S\"` [INFO] $message [Status] $status : success" | tee -a "${success_logs}"
                fi
}

如果我这样做,我会收到一封关于所有失败作业的电子邮件。

最佳答案

也可以使用 sendmail 命令:

sendmail user@example.com  < email.txt

使用邮件命令:

mail -a mail.txt -s "This is the failed job log" user@example.com

-a是附件,-s是主题

还有很多附件:

$(uuencode file1.txt file2.txt) | mailx -s "Subject" user@example.com

关于linux - 如何在 shell 脚本中为失败的作业发送电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43699496/

相关文章:

linux - 长时间运行时程序停顿

c - 结构与 union : structure has no member named

bash - bash 中嵌套循环的奇怪行为

python - 实现运行代码的死人开关

android - 在 adb shell 命令行中将 1 个命令的输出通过管道传输到其他命令

bash - Bash 中声明、排版和局部变量之间的区别

linux - 使用 SocketCAN 编写自定义 CAN 协议(protocol)

linux - 如何获取Linux进程“使用”的内存?

bash - 如何将 printf 语句的结果分配给变量(前导零)?

ruby - Windows,从 Ruby 运行 shell 脚本?