Crontab allows you to run tasks & processes in Linux automatically on a regular basis. Sometimes you may need to run shell script as cron job or execute shell script from crontab. In other words, you may want to regularly run shell script in an automated manner. You can easily do this in every Linux system. In this article, we will look at how to run shell script as cron job. This is a very common requirement by system administrators who wish to run a number of shell scripts on a regular basis, to automate various system related tasks.
How to Run Shell Script as Cron Job
Here are the steps to run shell script as cron job.
1. Create Shell Script
Open terminal and run the following command to create a blank shell script file e.g. backup.sh
$ sudo vi backup.sh
2. Add shell script
Let us say you want to create shell script to take backup of your MySQL database. In this case, add the following lines to your shell script. Replace test_user, test_password and web_db with your database username, password & database name respectively.
#!/bin/sh sudo mysql -utest_user -ptest_password web_db > db_backup.sql
Save and close the file.
3. Make Shell Script executable
Run the following command to make shell script executable.
$ sudo chmod +x backup.sh
4. Run Shell Script from Crontab
$ crontab -e
Add the following line to run the above shell script every day at 10.a.m. You can get the crontab statement as per your requirement using online crontab generator.
0 10 * * * sudo /home/backup.sh >/dev/null 2>&1
Please make sure to specify the full path to your shell script to avoid any “file not found” errors. Also use sudo keyword to avoid permission related errors.
In the above code “0 10 * * *” indicates that cronjob needs to be run everyday at 10.a.m. Then we specify the command to run shell script. Finally we direct any errors & messages to /dev/null.
You may modify the above command as per your requirement.
It is very useful to run shell scripts from crontab. You can use them to automate various system administration tasks such as restarting server, clearing log files, taking backups, sending emails and more.
How to Create Cron Job Using Shell Script
How to Get Current Directory in Shell Script
How to Get Current Directory in Python
How to Check Dependencies for Package in Linux
How to Iterate Over Multiple Lists in Python