如果任务失败发送电子邮件
Send email if task failed
我正在编写一个 shell 脚本,该脚本创建一个日志文件,记录它完成的所有任务。在脚本的最后,它创建了一个 tar 文件并 restarts 一个服务。
我希望脚本在 tar 进程失败或服务未备份时发送电子邮件。我不确定如何检查 tar 和服务 passed/failed.
这是一个 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" | user@domain.com << "the task failed"
更新:脚本不应中止,因为我希望服务在任何先前任务失败时再次尝试 start。
您可以检查每个步骤产生的exit status,并发送任何那些退出状态的邮件都会引发一个标志。
# 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" | user@domain.com << "the task failed"
fi;
这是一个使用函数的简单解决方案:
#!/bin/bash
failfunction()
{
if [ "" != 0 ]
then echo "One of the commands has failed!!"
#mail -s "Task failed" | user@domain.com << "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 "$?"
我正在编写一个 shell 脚本,该脚本创建一个日志文件,记录它完成的所有任务。在脚本的最后,它创建了一个 tar 文件并 restarts 一个服务。
我希望脚本在 tar 进程失败或服务未备份时发送电子邮件。我不确定如何检查 tar 和服务 passed/failed.
这是一个 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" | user@domain.com << "the task failed"
更新:脚本不应中止,因为我希望服务在任何先前任务失败时再次尝试 start。
您可以检查每个步骤产生的exit status,并发送任何那些退出状态的邮件都会引发一个标志。
# 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" | user@domain.com << "the task failed"
fi;
这是一个使用函数的简单解决方案:
#!/bin/bash
failfunction()
{
if [ "" != 0 ]
then echo "One of the commands has failed!!"
#mail -s "Task failed" | user@domain.com << "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 "$?"