Search code examples
linuxemailcronoutput-redirect

Linux cron job to email output from a command


I would like to run a cron job to backup some mysql databases by piping the output to a file and then emailing it.

Will the following work?

15 2 * * * root mysqldump -u root -pPASSWORD --all-databases | \
    gzip > /database_`data'+%m-%d-%Y'`.sql.gz | \
    mail -s "Report 05/06/07" [email protected] < /database_`data'+%m-%d-%Y'`.sql.gz

Solution

  • There are a couple of problems with your script, I have altered it below, note carefully the change of spaces, spelling of date and replacement of | for ;.

    The most interesting problem however is that mail unfortunately can't send attachments. You could use uuencode to embed the file in the mail using:

    15 2 * * * root mysqldump -uroot -pPASSWORD --all-databases | gzip > /database_`date +'%m-%d-%Y'`.sql.gz ; uuencode /database_`date +'%m-%d-%Y'`.sql.gz /dev/stdout | mail -s "Report 05/06/07" [email protected]
    

    Or if you want to have a proper MIME attachment use (You will need MetaMail installed):

    15 2 * * * root mysqldump -uroot -pPASSWORD --all-databases | gzip > /database_`date +'%m-%d-%Y'`.sql.gz ; metasend -b -t [email protected] -s "Report 05/06/07" -m application/gzip -f /database_`date +'%m-%d-%Y'`.sql.gz
    

    Or as above with mpack installed, instead of MetaMail:

    15 2 * * * root mysqldump -uroot -pPASSWORD --all-databases | gzip > /database_`date +'%m-%d-%Y'`.sql.gz ; mpack -s "Report 05/06/07" -c application/gzip /database_`date +'%m-%d-%Y'`.sql.gz [email protected]