How to Run Automated Scripts with Crontab

Learning crontab could be useful for any system maintenance or repetitive tasks you may need to do, such as file backups or system updates. As an example, I am using it as a way to do a ‘git clone’ a few times a day to keep a website’s contents up-to-date, as I have the website’s owner using Github for the website’s CMS.

First, you will want to make a script for the crontab. Use touch to create the script file, chmod +x to make it executable, and visudo to open up the sudoers file.

touch /path/to/script.sh
chmod +x /path/to/script.sh
sudo visudo

You may not have to do this, but sometimes your script may need to be run as sudo to do some of the commands. If your commands will need elevated privileges to run, add this line to the sudoers file:

linux_user ALL=(ALL:ALL) NO PASSWD:/path/to/script.sh

Now you can create the script. Here’s an example one that just prints out Hello!:

#!/bin/sh
echo "Hello!"

Once you have saved that file, you can start on the cron job. Start the crontab editor:

crontab -e

From here, go to the bottom of the page, and add a line to schedule a cron job. This will run the script once a minute, and log the output through journalctl, tagged with script-tag.

* * * * * /path/to/script.sh 2>&1 | logger -t script-tag

Now, you should be able to see the logs with the journalctl command. This will give you a live feed of updates from your script:

journalctl --follow -t script-tag

That’s all there is to it for the basics. If you want to set up different times for the cron job to run, the syntax is as follows:

mm hh dm MM dw command-to-execute
mm – minute (0-59)
hh – hour (0-23)
dm – Day of month (1-31)
MM – Month of year (1-12)
dw – Day of week (0-6 for Sunday to Saturday)

Leave a Reply

Your email address will not be published. Required fields are marked *