How do you CronJob a script to mail it to your INBOX

Many time we come across a situation where in we need to schedule a script and mail that report to our INBOX
If that is the case here is how we do it

There are 3 basic modes of crontab

  • crontab -l : lists all the scheduled commands/scripts for current user
  • crontab -l -u username : lists all the scheduled commands/scripts for specific user
  • crontab -e : edit the scheduled commands/scripts

Here is how it lists all cronjobs under current user

dbadm@linux122:~> crontab -l
# DO NOT EDIT THIS FILE - edit the master and reinstall.
# (/tmp/crontab.XXXX7mwgtU installed on Tue Nov 12 17:53:36 2013)
# (Cron version V5.0 -- $Id: crontab.c,v 1.12 2004/01/23 18:56:42 vixie Exp $)

####   BACKUPS

01 01 * * * /home/DB_BKPS/scripts/sample1_backup.sh
01 02 * * * /home/DB_BKPS/scripts/sample2_backup.sh

Say if you are in root user and want to list cronjobs for user dbadm

linux122:~ # crontab -l -u dbadm
# DO NOT EDIT THIS FILE - edit the master and reinstall.
# (/tmp/crontab.XXXX7mwgtU installed on Tue Nov 12 17:53:36 2013)
# (Cron version V5.0 -- $Id: crontab.c,v 1.12 2004/01/23 18:56:42 vixie Exp $)

####   BACKUPS

01 01 * * * /home/DB_BKPS/scripts/awdrt_backup.sh
01 02 * * * /home/DB_BKPS/scripts/gsrtc_backup.sh

You can edit the crontab to add/edit/delete the cronjobs with the command crontab -e

Give the path of the script as below

01 */1 * * * /path-of-script/script.sh 2>&1 | mail -s " Subject of the mail (Include `date` in subject for more accuracy)" your@emailadress

It has been scheduled for 1st min of every hour

So every time the script is executed as scheduled the output is sent to the mail address specified above

Have a Nice Day

No comments:

Post a Comment