Automate cron job creation using a Bash script

There is a pretty straight forward way to implement cron jobs using Bash shell. However, it’s a manual process and it looks like this:

  • Run `crontab -e` to open the current user crontab file using the default editor ( you need to select a default editor “nano, vim..” if it’s the first time )
  • Add the cron job; eg: `15 3 * * * /usr/bin/certbot renew –quiet`
  • Save the file ( `CTRL + X -> Y -> Enter` )

The above can be great and easy to do if you need to implement this once or twice. However, it could turn into a nightmare if you need to implement it on multiple servers, or if you simply need to add a cron job as a part of another process executed using a Bash script.

Don’t worry, there is a nice workaround to this issue. You can automate cron jobs creation by adding the existing cron jobs and your new cron job into a temporary file. After completing this step, you would need to copy the content of our temp file and use it as a replacement to the content of current user crontab.

So the final script should look something like this ( read Bash comments as they explain the purpose of each line ):


# If our cron job already exists, bail out.
if ! crontab -l &> /dev/null | grep -q "/usr/bin/certbot renew"; then
    # Copy the existing cron jobs into a temporary file
    crontab -l &> /dev/null > cronjobs.txt
    # Add our new cron job to the file
    echo "15 3 * * * /usr/bin/certbot renew --quiet" >> cronjobs.txt
    # Replace content of current user crontab with the content from our cron jobs file
    cat cronjobs.txt > /var/spool/cron/crontabs/"$USER"
    # Remove the temporary file
    rm cronjobs.txt 

Github Gist

Note that we have used a condition to make sure the cron job is only added if it doesn’t already exist. We’ve also used `&> /dev/null` to suppress errors and messages on `crontab -l` command.

Leave a comment