Linux cron job to email output from a command

7.1k views Asked by At

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
2

There are 2 answers

3
Lawrence Woodman On BEST ANSWER

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]
0
Decio On

I've tried the first option but had an error, with a small modification it worked fine:

15 2 * * * root mysqldump -e --user=root --password=PASSWORD --all-databases | gzip | uuencode `date +'%Y%m%d'`-database.sql.gz | mail -s "`date +'%Y%m%d'`-web1_iepe-wp.sql.gz mysqldump backup" [email protected]

Tks!