The post Using Cron to Automate Linux Tasks by Jack got me thinking that some users might be interested in a practical example. The following tutorial will explain how to setup a small script to backup MySQL databases on a Linux server which will be run daily using a cron job. The best way to start would be to read up on the introduction by Jack about Cron so that you got a understanding of the basics.
We start by creating the bash script first and continue with the cron job after the bash script has been tested to work as intended. All commands in the following paragraphs are executed from the command line.
This will create an empty text file in the vi editor. This will be the script that will be executed by the cron job on a daily basis.
/usr/bin/mysqldump -A -u [Username] -p[Password] | gzip > /backups/mysqldump`date +%m_%d_%y`.gz
Press i to enter insert mode and copy and paste the two lines above in the editor. What the script does is to use the mysqldump function to create a mysql backup and store it gzipped in the backups directory using mysqldumpDate.gz as the name with data being the day the backup was created.
The two variables [Username] and [Password] have to be edited and the username and password of a user with sufficient rights entered. It might also be necessary to change the location of the backup folder.
Press ESC to enter command mode and :x to save the file.
Execute the script to see if it is working correctly. It should create the dump of the MySQL database in the defined directory. It might be necessary to change the permission level of the backup.sh file if you get a permission error during execution.
chmod 755 backup.sh
If the script is working as intended it can be added as a cron job. The following command will open the user crontab list.
If you are in the vi editor you press i to enter insert mode again and add the following line
0 7 * * * /path/to/backup.sh
Please refer to the tutorial for a detailed instruction on how to set the cron job up to suite your needs. This one will execute the script every day on 7am.
It is a good idea to check back after the next execution to verify that everything is working as intended.Advertisement
Ghacks is a technology news blog that was founded in 2005 by Martin Brinkmann. It has since then become one of the most popular tech news sites on the Internet with five authors and regular contributions from freelance writers.