Link to home
Start Free TrialLog in
Avatar of Julian Matz
Julian MatzFlag for Ireland

asked on

Send output from bash script to mail

Hi!

I'm writing a simple bash script to place in /etc/cron.daily/. The script runs a couple of commands. What I'm wondering is how do I send all stdout and stderr to mail once the script has exited?
Avatar of Deepak Kosaraju
Deepak Kosaraju
Flag of United States of America image

schedule the script as follows under crond.daily
@daily <script name>  > /tmp/output 2>$1

@daily process.sh > /tmp/output 2>$1

in you script at the ending add mail process as
"cat |mail -s "" "
For Example:
I like to know number of process running with backup at midnight my process.sh contain
#!/bin/sh
ps -ef | grep -wi "backup.sh" | grep -v "grep"
d=`date +%D-%H:%S:`
`cat /tmp/output | mail -s "Backup Status on $d"  backupadmin@test.com`
(or)
`mail -s "Backup Status on $d" backupadmin@test.com < /tmp/output`


Avatar of Tintin
Tintin

By default cron will mail any output to the cronjob owner.
Avatar of Julian Matz

ASKER

@kosarajudeepak: I could do this if I used crontab but what if place the script to be executed in the following directory:
/etc/cron.daily

@Tintin: I only seem to be getting stderr (which is good since my mailbox would be flooded otherwise).
You can send the output from any cron job to a user by adding

MAILTO="user@domain.com"

or disable it by using

MAILTO=""

as the first line in the cron file, but it's universal for all jobs in the cron file. Sometimes you don't want the output from all the jobs sent. In these cases, the re-direct works better.
Its simple redirect the command output to a file like first command as > and following command's as appending. so every time when script runs /tmp/output will be overwritten by the first command output and followed by appending status output of remaining commands.
#!/bin/sh
output="/tmp/output"
ps -ef | grep -wi "backup.sh" | grep -v "grep" > $output
ps -ef | grep -wi "status.sh" | grep -v "grep" >> $output
ps -ef | grep -wi "restore.sh" | grep -v "grep" >> $output
d=`date +%D-%H:%S:`
`cat /tmp/output | mail -s "Backup Status on $d"  backupadmin@test.com`
(or)
`mail -s "Backup Status on $d" backupadmin@test.com < /tmp/output`
The easiest way is to do
#!/bin/bash
exec 1>/tmp/$$ 2>&1
 
...
 
mail -s "Script output" some@user </tmp/$$

Open in new window

Tintin can you explain the following I am not expert in Shell Scripting I used $* $1$2 etc but I never used $$ what it implies and what dose
exce 1>/tmp/$$ does
#!/bin/bash
exec 1>/tmp/$$ 2>&1
 
...
 
mail -s "Script output" some@user </tmp/$$

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Tintin
Tintin

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks, Tintin, that's exactly what I wanted to know.
-Julian