Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send email if task failed

Tags:

bash

shell

task

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.

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.

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

#!/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.

like image 756
user1052448 Avatar asked Oct 26 '25 07:10

user1052448


1 Answers

You can check the exit status produced 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;
like image 137
Alvaro Flaño Larrondo Avatar answered Oct 27 '25 21:10

Alvaro Flaño Larrondo