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

use*_*448 3 bash shell task

我正在编写一个shell脚本,该脚本创建一个日志文件,其中包含已完成的所有任务。在脚本的最后,它将创建一个tar文件并重新启动服务。

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

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

#!/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"
Run Code Online (Sandbox Code Playgroud)

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

Alv*_*ndo 7

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

# 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;
Run Code Online (Sandbox Code Playgroud)


小智 5

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

#!/bin/bash

failfunction()
{
    if [ "$1" != 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 "$?"
Run Code Online (Sandbox Code Playgroud)

  • `exit` 阻止了这种情况。 (5认同)