0

I am modifying a backup script to save multiple servers with multiple services and different configurations using bash on an Ubuntu server.

I save outputs from commands into a log file and sent these by mail. If the backup got an error from any process, I want to alert user with a specific mail subject, so I need to get if all processes were good or not and to keep all logs ordered.

I searched on all over the internet and I don't get any satisfying answer so, I am now asking to you...

What is the best way to do it ?

Should I use a separate configuration for each server ? Or each service get its script file calling what it needs ? Should I use source or execute scripts ? How could I just get if an error occured with no effects on logs ?

NB : I posted originally at https://superuser.com/questions/1155495/capture-outputs-with-bash-to-log-it-and-alert-user but it seems more appropriate on Server Fault. I will remove it if you confirm.

Loenix
  • 101
  • 1
  • 2

2 Answers2

3

If you're always emailing the log and just want to change the subject of the message, then I think something like this would be appropriate:

subject="Backup Log"
# >/some/log.txt will delete the file if it already exists
# "if ! command" checks to see if the command exited with an nonzero code
if ! backup_command >/some/log.txt 2>&1; then
  subject="$subject First Backup Failed"
fi
# >>/some/log.txt will append output to the file
if ! other_backup_command >>/some/log.txt 2>&1; then
  subject="$subject Second Backup Failed"
fi
# etc
mail -s "$subject" < /some/log.txt

This assumes that your backup commands use their exit code to indicate failure.

DerfK
  • 19,493
  • 2
  • 38
  • 54
  • I finally used temporarily file like you suggest, I didn't get any better solution. Thank you ! But this is harder because I have to get all logs separately, this is a child script that is running sub-commands and mother script don't get the return code. – Loenix Jan 25 '17 at 08:49
1

To capture output from the scripts you can either redirect the output of the script to a log file.

my_script.sh 2>&1 >> log.txt

or capture the output from the individual commands in the script to a log file.

#!/bin/bash
# my_script.sh
command_1 2>&1 >> log.txt
command_2 2>&1 >> log.txt

The 2>&1 ensures that errors are also captured.

bao7uo
  • 1,704
  • 12
  • 24