bash 如果任务失败,发送电子邮件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32996456/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 13:41:01  来源:igfitidea点击:

Send email if task failed

bashshelltask

提问by user1052448

I'm writing a shell script that creates a log file of all the tasks it completed. At the very end of the script it creates a tar file and restarts a service.

我正在编写一个 shell 脚本,用于创建它完成的所有任务的日志文件。在脚本的最后,它会创建一个 tar 文件并重新启动服务。

I would like the script to send an email if the tar process failed or if the service didn't start back up. I'm not sure how to check if the tar and service passed/failed.

如果 tar 进程失败或服务没有启动备份,我希望脚本发送一封电子邮件。我不确定如何检查 tar 和服务是否通过/失败。

Here's an example of the shell script without checking if the tar or service completed...

这是一个 shell 脚本示例,不检查 tar 或服务是否完成...

#!/bin/bash

# Shutdown service
service $SERVICE stop

# Task 1
command > some1.log

# Task 2
command > some2.log

# Task 3
command > some3.log

# Compress Tar file
tar -czf logfiles.tar.gz *.log

# Start service
service $SERVICE start

# mail if failed
mail -s "Task failed" | [email protected] << "the task failed"

Update: The script should not abort as I want the service to attempt to start again if any of the prior tasks did fail.

更新:脚本不应中止,因为如果任何先前的任务失败,我希望服务尝试重新启动。

回答by Alvaro Fla?o Larrondo

You can check the exit statusproduced by each step, and send the mail of any of those exit status raises a flag.

您可以检查每个步骤产生的退出状态,并发送任何退出状态的邮件会引发一个标志。

# Compress Tar file
tar -czf logfiles.tar.gz *.log

TAR_EXIT_STATUS=$?

# Start service
service $SERVICE start

SERVICE_EXIT_STATUS=$?

# mail if failed
if [ $TAR_EXIT_STATUS -ne 0 ] || [ $SERVICE_EXIT_STATUS -ne 0 ];then
    mail -s "Task failed" | [email protected] << "the task failed"
fi;

回答by Alvaro Fla?o Larrondo

Here is a simple solution using a function:

这是一个使用函数的简单解决方案:

#!/bin/bash

failfunction()
{
    if [ "" != 0 ]
    then echo "One of the commands has failed!!"
         #mail -s "Task failed" | [email protected] << "the task failed"
         exit
    fi
}

# Shutdown service
service $SERVICE stop 
failfunction "$?"

# Task 1
command > some1.log 
failfunction "$?"

# Task 2
command > some2.log 
failfunction "$?"

# Task 3
command > some3.log 
failfunction "$?"

# Compress Tar file
tar -czf logfiles.tar.gz *.log 
failfunction "$?"

# Start service
service $SERVICE start 
failfunction "$?"