Sometimes you may need to automate cron job creation. You can easily create cron job using shell script. In this article, we will look at how to add cron job or schedule cron job using Shell script. This approach can be used in all Linux distributions since these commands are available in every Linux.
How to Create Cron Job using Shell Script
Here are the steps to create cron job using shell script. Let us say you want to run a script /home/test.sh every day at 10.a.m. then here is the crontab statement for it. You can use any of the online crontab generator to get the crontab statement.
0 10 * * * sudo /home/test.sh >/dev/null 2>&1
1. Copy Current Crontab
Open terminal and run the following command to copy the content of current crontab file to another temporary file cron_bkp
$ sudo crontab -l > cron_bkp
2. Add new cronjob
Run the following command to add new cronjob to the temporary file.
echo "0 10 * * * sudo /home/test.sh >/dev/null 2>&1" >> cron_bkp
In the above statement, we echo the cronjob command and use >> operator to append it to cron_bkp file. Please note, if you want to overwrite existing crontab with new one, just use > operator instead of >> above.
3. Update crontab
Finally, we copy the temporary file back to crontab using the following command. This will install new crontab.
$ sudo crontab cron_bkp
You may delete the temporary file if you don’t need it.
$ sudo rm cron_bkp
4. Shell Script to Create Cronjob
Here is a simple shell script to create cronjob, using the above code.
#!/bin/sh sudo crontab -l > cron_bkp sudo
echo "0 10 * * * sudo /home/test.sh >/dev/null 2>&1" >> cron_bkpsudo crontab cron_bkp sudo rm cron_bkp
Please note, if you want to overwrite existing crontab with new one, just use > operator instead of >> above.
That’s it. In this article, we have learnt how to automate cronjob creation using shell script. Basically, you need to copy the content of your existing crontab into a temporary file, append new cron job to it, and install crontab using this temporary file.
It is very useful to automate cronjobs using shell scripts, if you want to add or schedule cronjob without opening terminal every time, or avoid shell interaction. This is also useful if you want to repeatedly create cronjobs in your system.
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
How to Disable GZIP Compression in Apache