问题
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" user@example.com < /database_`data'+%m-%d-%Y'`.sql.gz
回答1:
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" user@domain.com
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 user@domain.com -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 user@domain.com
回答2:
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" user@domain.com
Tks!
来源:https://stackoverflow.com/questions/5190215/linux-cron-job-to-email-output-from-a-command