Linux: Add cronjob using a bash script.

We all know and love cronjobs, cronjobs allows us to execute a command or a script in the future. It can be tedious boring and error prone…

Linux: Add cronjob using a bash script.
Photo by Andrik Langfield on Unsplash

We all know and love cronjobs, cronjobs allows us to execute a command or a script in the future. It can be tedious boring and error prone to use vim or nano to edit our crontab on each host we want to schedule a task; let's see how we can automate this using bash.

Creating the script

In the following scenario we will create a bash script that will do the following

  • Insert a cronjob that will restart nginx every day at 04:10 am.
  • reload cron in order to apply the new configuration.

Open an editor and enter the following.#!/bin/bash
crontab -l | { cat; echo "10 04 * * * /bin/systemctl restart nginx"; } | crontab - && systemctl reload crond

Save the script as my_cronjob.sh and make it executablechmod +x ./my_cronjob.sh

Explaining the script

  • crontab -l pipes the script to the cat command
  • echo appends in the end of the cat command the new cronjob
  • | crontab — re-writes the current user crontab
  • && systemctl reload reloads cron configuration.

How to apply this in many servers

You can scp the script to the home directory of the user that you want to apply to the crontabscp ./my_cronjob <user>@<host>:~

Then login to each server and execute the script or use ssh to remote execute it.ssh <user>@<host> 'cd ~ && ./my_cronjob.sh'

And that's all! now you have learned how to insert cronjobs using a script.

I hope you found this article useful!