Reputation: 6694
I have this line in crontab:
* * * * * /var/www/dir/sh/mysql_dumb.sh | mail -s "mysql_dump" example@mail.com
(every minute only a sample)
So, all works fine, but the email is empty.
UPDATE:
The output from mysql_dumb.sh is a *.sql
file and they save the file in a directory.
How can I send a copy (*.sql file) from this output -> mysql_dumb.sh
to my email?
mysql_dumb.sh:
#!/bin/bash
PATH=/usr/bin:/bin
SHELL=/bin/bash
/usr/bin/mysqldump -u USER -pPASS DATABASE > /var/www/dir/backup/backup_DB_`date +%d_%m_%Y`.sql
Upvotes: 32
Views: 74721
Reputation: 6272
If you want to store your cron job's output on the file on server and also want to send that output file to your mail address then you can use below command.
And you can use it on cronjob to automatically run on specific interval of time, here i am dumping mysql db and sending it to my mail with attachment of dumped sql
file.
* * * * * mysqldump --user username --password='p@ssword' DBNAME | gzip > /home/user/db_backup/db_backup_`date +\%d-\%m-\%Y-\%H-\%M`.sql.gz && mailx -a /home/user/db_backup/db_backup_`date +\%d-\%m-\%Y-\%H-\%M`.sql.gz -s 'database backup date:'`date +\%d-\%m-\%Y-\%H:\%M` example@gmail.com
Upvotes: 0
Reputation: 1222
From a crond perspective more accurate is to place in to your cron:
MAILTO=example@mail.com
* * * * * /var/www/dir/sh/mysql_dumb.sh
* * * * * /var/www/dir/sh/other.sh
* * * * * /var/www/dir/sh/other2.sh
Upvotes: 42
Reputation: 402
Look at the last line of mysql_dumb.sh:
/usr/bin/mysqldump -u USER -pPASS DATABASE > /var/www/dir/backup/backup_DB_`date +%d_%m_%Y`.sql
The >
is redirecting the output of mysqldump
to the file /var/www/dir/backup/backup_DB_
date +%d_%m_%Y.sql
Do you want to store a backup of the database locally?
If not, take out the the > /var/www/dir/backup/backup_DB_`date +%d_%m_%Y`.sql
and put the crontab entry back to
* * * * * /var/www/dir/sh/mysql_dump.sh 2>&1 | mail -s "mysql_dump" example@mail.example
If you do want a copy of the file locally, I would suggest using tee
which will write the output to the file and put the output back out on stdout, which will later be picked up by crontab.
I would change the last line of mysql_dumb.sh
to be:
/usr/bin/mysqldump -u USER -pPASS DATABASE | tee /var/www/dir/backup/backup_DB_`date +%d_%m_%Y`.sql
Again I would change the crontab entry back to:
/usr/bin/mysqldump -u USER -pPASS DATABASE > /var/www/dir/backup/backup_DB_`date +%d_%m_%Y`.sql
The advantage here is mail can read the information from stdout and isn't dependent on the file being written and then read correctly. While that may be a small difference, in my experience using tee will be more reliable.
Upvotes: 2
Reputation: 782564
If the script is reporting errors, they may be going to stderr
, but you're only redirecting stdout
. You can redirect stderr
by adding 2>&1
to the command:
* * * * * /var/www/dir/sh/mysql_dump.sh 2>&1 | mail -s "mysql_dump" example@mail.example
Upvotes: 47