Cronjobs – An effective Linux utility

Cron, an Unix term stands for Command Run ON. It is very useful utility in Unix/Linux specially for SysAdmins who might like to schedule different tasks on different times for different purposes. Most frequently it is used for running scripts and creating backups. It’s a command based utility, where we can schedule a task on a given time to run. It’s format looks like the following:

MIN  HOUR  DOM  MON  DOW  CMD

MIN = Minutes[0-59] , HOUR = Hour[0-23] , DOM = Day of month[1-31] , MON = Month[1-12] , DOW = Day of week[0-6] , CMD = Command to run

00  06  *  *  *  /home/bak/cback.sh

The above command will run on the following time and will trigger a script at home bak directory called cback.sh:

00 = 0th minute

06 = 6AM at morning

* = Every day

* = Every month

* = Every day of the week

Normally * represents ‘Every’ word here, if you want to run it every hour. Replace 06 with *, which will trigger the script every hour.

understanding cronYou can see the cron jobs by running crontab -l in terminal and add/edit them via crontab -e .

Read Linux man pages in terminal for more knowledge or read this article for more deep understanding.

Delete cron mails

There are many ways to delete cron mails and empty the inbox which is filled by cron job every time it runs. Some time we are running multiple scripts/files every minute. So cron send mail for that specific user to inform about the cron task and the mail, if there is any thing to output, it will be in the mail.

But some time we don’t want any mails created by cron to send. Its because we know our scripts are running fine.

I am going to mention three methods here.

Method-1: Running a simple command in terminal,

1- Open terminal and became any user, you want to delete mails from his/her inbox.

2- This way will clear all the inbox.

3- Write the following command in terminal now:

cat /dev/null >/var/mail/username

Change username in above.

Method-2: Running a bash script in terminal,

1- Open any of your text editor and write the following code in it:

#!/bin/sh

echo ‘d *’ | mail -N

exit 0

2- Save it as any file name you want, i would save it cron.sh.

3- Now run it in terminal like this:

sh /var/www/cron.sh

Remember to give correct path in the above line.

Method-3: Another way is to delete one by one, but that will be pain in the neck if you have hundreds or thousands of mails in the inbox. But if you want to delete a specific message so you can do it like this way, 1st enter to the user mail directory for example:

cd /var/mail/username

Path and username can be changed according to user and distribution.

d 1 2 6 10

The above line will delete messages 1,2,6,10 respectively by using the ‘mail’ command.

Hope it would help.