Monday, 28 January 2013

Package Management - YUM


Task: Display list of updated software (security fix)

Type the following command at shell prompt:
# yum list updates
Task: Patch up system by applying all updates

To download and install all updates type the following command:
# yum update
Task: List all installed packages

List all installed packages, enter:
# rpm -qa
# yum list installed
Find out if httpd package installed or not, enter:
# rpm -qa | grep httpd*
# yum list installed httpd
Task: Check for and update specified packages

# yum update {package-name-1}
To check for and update httpd package, enter:
# yum update httpd
Task: Search for packages by name

Search httpd and all matching perl packages, enter:
# yum list {package-name}
# yum list {regex}
# yum list httpd
# yum list perl*

Task: Install the specified packages [ RPM(s) ]

Install package called httpd:
# yum install {package-name-1} {package-name-2}
# yum install httpd
Task: Remove / Uninstall the specified packages [ RPM(s) ]

Remove package called httpd, enter:
# yum remove {package-name-1} {package-name-2}
# yum remove httpd
Task: Display the list of available packages

# yum list all
Task: Display list of group software

Type the following command:
# yum grouplist


Task: Install all the default packages by group

Install all 'Development Tools' group packages, enter:
# yum groupinstall "Development Tools"
Task: Update all the default packages by group

Update all 'Development Tools' group packages, enter:
# yum groupupdate "Development Tools"
Task: Remove all packages in a group

Remove all 'Development Tools' group packages, enter:
# yum groupremove "Development Tools"
Task: Install particular architecture package

If you are using 64 bit RHEL version it is possible to install 32 packages:
# yum install {package-name}.{architecture}
# yum install mysql.i386
Task: Display packages not installed via official RHN subscribed repos

Show all packages not available via subscribed channels or repositories i.e show packages installed via other repos:
# yum list extras


Task: Display what package provides the file

You can easily find out what RPM package provides the file. For example find out what provides the /etc/passwd file:
# yum whatprovides /etc/passwd

You can use same command to list packages that satisfy dependencies:
# yum whatprovides {dependency-1} {dependency-2}
Refer yum command man page for more information:
# man yum

How To Download a RPM Package Using yum Command Without Installing On Linux

You need to install plugin called yum-downloadonly. This plugin adds a --downloadonly flag to yum so that yum will only download the packages and not install/update them. Following options supported by this plugin:

[a] --downloadonly : don't update, just download a rpm file
[b] --downloaddir=/path/to/dir : specifies an alternate directory to store packages such as /tmp

# yum install yum-downloadonly

Download httpd package but don't install/update, enter:
# yum update httpd -y --downloadonly

By default package will by downloaded and stored in /var/cache/yum/ directory. But, you can specifies an alternate directory to store packages such as /opt, enter:
# yum update httpd -y --downloadonly --downloaddir=/opt

Method # 2: yum-utils.noarch Package

yum-utils is a collection of utilities and examples for the yum package manager. It includes utilities by different authors that make yum easier and more powerful to use. These tools include: debuginfo-install, package-cleanup, repoclosure, repodiff, repo-graph, repomanage, repoquery, repo-rss, reposync, repotrack, verifytree, yum-builddep, yum-complete-transaction, yumdownloader, yum-debug-dump and yum-groups-manager.
# yum -y install yum-utils.noarch
Now use the yumdownloader command which is a program for downloading RPMs from Yum repositories. Type the following command to download httpd rpm file:
# yumdownloader httpd
Sample outputs:

Loaded plugins: rhnplugin
httpd-2.2.3-31.el5_4.2.x86_64.rpm | 1.2 MB 00:00


How Do I Extract Downloaded RPM File?

Type the command as follows:
# rpm2cpio httpd-2.2.3-31.el5_4.2.x86_64.rpm | cpio -idmv

Howto Setup yum repositories to update or install package from ISO CDROM Image

Creation of yum repositories is handled by a separate tool called createrepo, which generates the necessary XML metadata. If you have a slow internet connection or collection of all downloaded ISO images, use this hack to install rpms from iso images.
Step # 1: Mount an ISO file

Type the following command (replace iso file name with the actual iso file):
# yum install createrepo
# mkdir -p /mnt/iso/{1,2,3}
# mount -o loop /path/to/centos1.iso /mnt/iso/1
Step # 2: Create a repository

Use createrepo to generate the necessary XML metadata. Type the following commands:
# cd /mnt/iso
# createrepo .
Clean repo, enter:
# yum clean all
Step # 3: Create config file

You need to create a repo config file in /etc/yum.repos.d/ directory.
# vi /etc/yum.repos.d/iso.repo
Append following text:
[My ISO Repository]
baseurl=file:///mnt/iso
enabled=1
Save and close the changes.

Now use yum command to install packages from ISO images:
# yum install package-name


RHEL / CentOS: yum Lists / Installs Only Security Updates

You can easily find out security patches related information using yum-security plugin. This plugin adds the options --security, --cve, --bz and --advisory flags to yum and the list-security and info-security commands. The options make it possible to limit list/upgrade of packages to specific security relevant ones. The commands give you the security information.
Install Plugin

Type the following command:
# yum install yum-security
How Do I Display Available Security Updates?

Type the following command:
# yum list-security
Sample Outputs: Loaded plugins: rhnplugin, security
RHSA-2009:1148-1 security httpd-2.2.3-22.el5_3.2.x86_64
RHSA-2009:1148-1 security httpd-devel-2.2.3-22.el5_3.2.i386
RHSA-2009:1148-1 security httpd-manual-2.2.3-22.el5_3.2.x86_64
RHSA-2009:1148-1 security mod_ssl-1:2.2.3-22.el5_3.2.x86_64
list-security done


To list all updates that are security relevant, and get a reutrn code on whether there are security updates use:
# yum --security check-update
To get a list of all BZs that are fixed for packages you have installed use:
# yum list-security bugzillas
To get the information on advisory RHSA-2009:1148-1 use:
# yum info-security RHSA-2009:1148-1

To get an info list of the latest packages which contain fixes for Bugzilla 3595; CVE # CVE-2009-1890 and advisories RHSA-2009:1148-1, use:
# yum --bz 3595 --cve CVE-2009-1890 --advisory RHSA-2009:1148-1 info updates
How Do I Install All The Security Updates Only?

Type the following command to download and install all the available security updates:
# yum update --security
Howto: Add a new yum repository to install software under CentOS / Redhat Linux
Understanding yum repository

yum repository configured using /etc/yum.conf file. Additional configuration files are also read from the directories set by the reposdir option (default is /etc/yum.repos.d and /etc/yum/repos.d.
RPMforge repository

Usually repository carries extra and useful packages. RPMforge is one of such repository. You can easily configure RPMforge repository for RHEL5 just by running following single RPM command:
# rpm -Uhv http://apt.sw.be/packages/rpmforge-release/rpmforge-release-0.3.6-1.el5.rf.i386.rpm
For 64 bit RHEL 5 Linux, enter:
# rpm -Uhv http://apt.sw.be/packages/rpmforge-release/rpmforge-release-0.3.6-1.el5.rf.x86_64.rpm

Now you can install software from RPMforge.
Force yum update Command To Exclude Certain Packages

Yum uses a configuration file at /etc/yum/yum.conf or /etc/yum.conf. You need to place exclude directive to define list of packages to exclude from updates or installs. This should be a space separated list. Shell globs using wildcards * and ?) are allowed.
How do I exclude php and kernel packages when I use "yum update"?

Open /etc/yum.conf file:
# vi /etc/yum.conf
Append following line under [main] section, enter:
exclude=php* kernel*
At the end, it should look like as follows:

[main]
cachedir=/var/cache/yum
keepcache=0
debuglevel=2
logfile=/var/log/yum.log
distroverpkg=redhat-release
tolerant=1
exactarch=1
obsoletes=1
gpgcheck=1
plugins=1
exclude=php* kernel*

# Note: yum-RHN-plugin doesn't honor this.
metadata_expire=1h

# Default.
# installonly_limit = 3

# PUT YOUR REPOS HERE OR IN separate files named file.repo
# in /etc/yum.repos.d

yum --exclude command line option

Finally, you can skip yum command updates on command line itself using following syntax:
# yum --exclude=package* update
# yum --exclude=php* update
# yum --exclude=kernel* update
Red hat / CentOS / Fedora Send Yum Package Update Notification Via Email

RHEL / Fedora / CentOS has yum-updatesd, which provides notification of updates which are available to be applied to your system. This notification can be done either
via syslog, email or over dbus. Configuration is done via the /etc/yum/yum-updatesd.conf file.

Open /etc/yum/yum-updatesd.conf file, enter:
# vi /etc/yum/yum-updatesd.conf
Setup variables as follows:
emit_via = email
# who to send the email to:
email_to = admin@example.com
# who send the notifications
email_from = adm@staff.example.com

Here is complete working config file:

[main]
# how often to check for new updates (in seconds)
run_interval = 3600
# how often to allow checking on request (in seconds)
updaterefresh = 600

# how to send notifications (valid: dbus, email, syslog)
emit_via = email
# who to send the email
email_to = admin@example.com

# who send the notifications
email_from = adm@staff.example.com
#
# should we listen via dbus to give out update information/check for
# new updates
dbus_listener = yes

# automatically install updates
do_update = no
# automatically download updates
do_download = no
# automatically download deps of updates
do_download_deps = no


Save and close the file. Restart notification yum-updatesd service:
# /etc/init.d/yum-updatesd restart
Sample email sent by yum notification
Hi,
This is the automatic update system on node02.nixcraft.co.in.

There are 2 package updates available. Please run the system updater.

Packages available for update:

device-mapper-multipath
kpartx

Thank You,
Your Computer

Using yum to install unsigned local rpm files

If yum is complaining when you’re trying to install a file you downloaded. Try to temporary change the variable gpgcheck=1 to gpgcheck=0 in the file /etc/yum.conf. This disables the signature checking.

Additional Repositories

http://wiki.centos.org/AdditionalResources/Repositories
epel

· http://fedoraproject.org/wiki/EPEL

· http://download.fedora.redhat.com/pub/epel/5/x86_64/repoview/

Install Repository: Install Key:
rpm --import http://download.fedora.redhat.com/pub/epel/RPM-GPG-KEY-EPEL


Verify repository package: you should get "(sha1) dsa sha1 md5 gpg OK"
rpm -K http://download.fedora.redhat.com/pub/epel/5/x86_64/epel-release-5-3.noarch.rpm


Install Repository:
rpm -Uvh http://download.fedora.redhat.com/pub/epel/5/x86_64/epel-release-5-3.noarch.rpm



rpmfusion

· http://rpmfusion.org/Configuration

Install epel and enable epel-testing at this time. Most packages are still in rpmfusion testing repository rpm --import
rpm -ivh http://download1.rpmfusion.org/free/el/updates/testing/5/i386/rpmfusion-free-release-5-0.1.noarch.rpm
rpm -ivh http://download1.rpmfusion.org/nonfree/el/updates/testing/5/i386/rpmfusion-nonfree-release-5-0.1.noarch.rpm

rpmforge

· https://rpmforge.net/

· http://apt.sw.be/redhat/el5/en/

Installing repository:

rpm --import http://dag.wieers.com/rpm/packages/RPM-GPG-KEY.dag.txt

rpm -K http://apt.sw.be/redhat/el5/en/x86_64/rpmforge/RPMS/rpmforge-release-0.3.6-1.el5.rf.x86_64.rpm

rpm -Uvh http://apt.sw.be/redhat/el5/en/x86_64/rpmforge/RPMS/rpmforge-release-0.3.6-1.el5.rf.x86_64.rpm


To seach for a application: Yum will search all your enabled repos and tell you where you can obtain the package from

CentOS / RHEL Configure Yum Automatic Update Retrieval and Installation

The yum command line tool is used to install and update software packages under RHEL / CentOS Linux server. I know how to apply updates using yum update command line, but I'd like to use cron to manually update packages where appropriate. How do I configure yum to install software patches / updates automatically with cron?

You can use yum-updatesd service provided with CentOS / RHEL servers. However, this service provides a few overheads. You can create daily or weekly updates with the following shell script. Create
/etc/cron.daily/yumupdate.sh to apply updates one a day.
/etc/cron.weekly/yumupdate.sh to apply updates once a week.

Sample shell script to update system

A shell script that instructs yum to update any packages it finds via cron:

#!/bin/bash
YUM=/usr/bin/yum
$YUM -y -R 120 -d 0 -e 0 update yum
$YUM -y -R 10 -e 0 -d 0 update

(Code listing -01: /etc/cron.daily/yumupdate.sh)

Where,
First command will update yum itself and next will apply system updates.
-R 120 : Sets the maximum amount of time yum will wait before performing a command
-e 0 : Sets the error level to 0 (range 0 - 10). 0 means print only critical errors about which you must be told.
-d 0 : Sets the debugging level to 0 - turns up or down the amount of things that are printed. (range: 0 - 10).
-y : Assume yes; assume that the answer to any question which would be asked is yes.

Make sure you setup executable permission:
# chmod +x /etc/cron.daily/yumupdate.sh


Yum Check or Install Updates Script

Split into two sections, one script is for all package updates, and the other script is for letting us know if we need to reboot when a new kernel package has been installed.

Script to check for updates:

check-yum-updates.sh

#!/bin/bash
#
# check-yum-updates.sh
#
# checks for yum updates and emails if there are any available
#
#
# Eric Thern
# Zoidial Incorporated
# http://www.zoidial.com
#
# last update:
# Dec 30, 2008
#

#
# change this to your email
#
email="youremail@youremail.com"

#
# no need to change anything below here
#

yumtmp="/tmp/yum-check-update.$"
yum="/usr/bin/yum"

$yum check-update >& $yumtmp

yumstatus="$?"

hostname=$(/bin/hostname)

case $yumstatus in
0)
# no updates!
exit 0
;;
*)
date=$(date)
number=$(cat $yumtmp | egrep '(.i386|.x86_64|.noarch|.src)' | wc -l)
updates=$(cat $yumtmp | egrep '(.i386|.x86_64|.noarch|.src)')
echo "
There are $number updates available on host $hostname at $date

The available updates are:
$updates
" | /bin/mail -s "UPDATE: $number updates available for $hostname" $email
;;
esac

# clean up

rm -f /tmp/yum-check-update.*

Script to check kernel (here we use 'ovzkernel' since we're running with an openvz kernel, if you have a stock centos kernel, change this to 'kernel')

check-yum-kernel.sh

#!/bin/bash
email=youremail@youremail.com
latestkernel=$(rpm -q ovzkernel |tail -n1|sed -e 's/kernel-//')

echo "$latestkernel"

if uname -a | grep -qv "$latestkernel"; then
echo "Running Kernel is" `uname -r` "but latest installed rpm is ${latestkernel}" |\
mail -s "UPDATE: ${HOSTNAME} reboot required" $email
fi;

Crontab entries:

30 21 * * * /root/bin/check-yum-updates.sh >/dev/null 2>&1
30 21 * * * /root/bin/check-yum-kernel.sh >/dev/null 2>&1

Run at 9:30 every night. Change times and paths to suit.


CentOS patching --exclude=kernel,kernel-headers

In my normal everyday job, I am tasked with managing and maintaining about 30-40 production CentOS servers. Being a security guy, I maintain a pretty rigorous patching routine. However, because these servers are customer production servers, one very important caveat is that I need to do everything I can to minimize customer downtime.

Normally when I patch a server, my routine is:

yum check-update (check what updates are available)

yum -y update (update everything)

And if the list produced by check-update shows the kernel or kernel-headers packages in the list, I promptly reboot the server. This translates into about 5 minutes of downtime for the customer as the server reboots.

So that got me thinking. Is every kernel update critical or can they easily be delayed? So then I stumbled across this excellent plug-in for yum.

yum-changelog-1.1.10-9.el5.centos

Name : yum-changelog
Arch : noarch
Version: 1.1.10
Release: 9.el5.centos
Size : 12 k
Repo : installed
Summary: Yum plugin for viewing package changelogs before/after updating
Description:
This plugin adds a command line option to allow viewing package changelog
deltas before or after updating packages.

Perfect! That will allow me to see exactly what is changing with each new version of the kernel. So I install that with:

yum install yum-changelog

Now we can use yum to show us the change log for certain packages. So, if I want to see the change log for the kernel related package, I could run something like:

yum update kernel kernel-headers --changelog

This will produce output similiar to:

Changes in packages about to be updated:

kernel-headers - 2.6.18-92.1.22.el5.x86_64
* Wed Dec 17 06:00:00 2008 Karanbir Singh [2.6.18-92.1.22.el5.centos]
- Roll in CentOS Branding

* Sat Dec 6 06:00:00 2008 Jiri Pirko [2.6.18-92.1.22.el5]
- [misc] hugepages: ia64 stack overflow and corrupt memory (Larry Woodman ) [474347 472802]
- [misc] allow hugepage allocation to use most of memory (Larry Woodman ) [474760 438889]


Ah, ha. As I suspected. Two memory related bugfixes and CentOS branding. Because we are currently not expirencing any memory related issues, this patch does NOT rate as critical and warrent immediate customer downtime. This can be delayed.

So now I can apply the other patches and exclude the kernel upgrades with:

yum update --exclude=kernel,kernel-headers

Now, I have a script that runs nightly on all my CentOS servers. This script gathers nightly statistics, logs entries, etc from my servers and emails it to me. This is pretty much jsut a CentOS port of my old Gentoo Update Script, with some CentOS speficic changes and additional features. The other thing it does, is generate a list (via yum check-update) of all the updates required. So the question now is, now can I get this interactive command to run via an automated script? The easiest way I could come up with is:

echo n | yum update kernel kernel-headers --changelog

Probably not the cleanest way, but does the job very well.


CentOS: Install Packages Via yum Command Using DVD / CD as Repo

CentOS Linux comes with CentOS-Media.repo which is used to mount the default locations for a CDROM / DVD on CentOS-5. You can use this repo and yum to install items directly off the DVD ISO that we release. Open /etc/yum.repos.d/CentOS-Media.repo file, enter:
# vi /etc/yum.repos.d/CentOS-Media.repo
Make sure enabled is set to 1:
enabled=1
Save and close the file. To use repo put your DVD and along with the other repos, enter:
# yum --enablerepo=c5-media install pacakge-name
To only use the DVDmedia repo, do this:
# yum --disablerepo=\* --enablerepo=c5-media install pacakge-name
OR use groupinstall command
# yum --disablerepo=\* --enablerepo=c5-media groupinstall 'Virtualization'




Howto Setup yum repositories to update or install package from ISO CDROM Image

yum (Yellow dog Updater Modified) is a package manager for RPM compatible Linux systems such as CentOS, Fedora core and latest Redhat Enterprise Linux.

So how do you use yum to update / install packages from an ISO of CentOS / FC / RHEL CD?

Creation of yum repositories is handled by a separate tool called createrepo, which generates the necessary XML metadata. If you have a slow internet connection or collection of all downloaded ISO images, use this hack to install rpms from iso images.

Step # 1: Mount an ISO file

Type the following command (replace iso file name with the actual iso file):
# yum install createrepo
# mkdir -p /mnt/iso/{1,2,3}
# mount -o loop /path/to/centos1.iso /mnt/iso/1

Step # 2: Create a repository

Use createrepo to generate the necessary XML metadata. Type the following commands:
# cd /mnt/iso
# createrepo .
Clean repo, enter:
# yum clean all

Step # 3: Create config file

You need to create a repo config file in /etc/yum.repos.d/ directory.
# vi /etc/yum.repos.d/iso.repo
Append following text:
[My ISO Repository]
baseurl=file:///mnt/iso
enabled=1
Save and close the changes.
Now use yum command to install packages from ISO images:
# yum install package-name

Crontab



What is a Crontab?
A cron is a utility that allows tasks to automatically run in the background of the system at regular intervals by use of the cron daemon. Crontab (CRON TABle) is a file which contains the schedule of cron entries to be run and at what times they are to be run. This can be quite useful. For example, you may have a personal temporary directory that you wish to be cleaned out once a day to keep your quota from being exceeded. This is where cron scheduling comes in to play. Not all systems allow for a cron schedule to be setup. You need to see your system administrator to see if it is available on your system.

 
How does it work?
A cron schedule is a simple ASCII text file. Each user has their own cron schedule. This is normally located in /var/spool/cron/crontabs for linux machines. The crontab files are not edited (or created) directly and you do not have access to the file without invoking it from the crontab command. You may not use any text editor you wish. You must use the text editor that has been specified in you system variables (see your system administrator for these). The text editor vi is usually the default text editor. The editor must be invoked using the -e switch. To create a cron schedule type:
crontab -e
The text editor vi will open a blank window for the "crontab entries" to be entered. Each line represents a seperate crontab entry (hereafter referred to as "cron jobs"). (To add comments place # before any text.). If you are not completely familiar with the vi editor you may want to see a Unix book (such as UNIX In A Nutshell).
Each cron job has at least 6 sections. Each section is separated by a single space, but the final section may have spaces within it. No spaces are allowed within Sections 1-5, only between them. Sections 1-5 are indicate when and how often you want the task (the sixth position) to be executed. All time are local times not GMT.
Special Note: If the computer system running the crontab is down, the crontab will not run as well. When the system comes back up, the crontab will resume its normal activity, but will not go back and run the jobs that were missed due to the system being down.
Here is how positions 1-5 are layed out:
1 Minute 0-59
2 Hour 0-23 (0 = midnight)
3 Day 1-31
4 Month 1-12
5 Weekday 0-6 (0 = Sunday)
An asterisk (*) is used to indicate that every instance (i.e. every hour, every weekday, etc.) of the particular time period will be used.
If you wish to use more than one instance of a particular time periods, then seperate the times by a comma. If you wish for continuous execution, the start and stop items are separated by a dash. For example, if you wanted to run your command at :05 and :35 past the hour, every hour, Monday through Friday, then your time stamp would look like this:
5,35 * * * 1-5
The sixth position indicates which task will be run at the given time(s). For example, if you wanted to remove all of the files in you "temp" directory every morning at 4:45 AM, your command would look:
45 4 * * * rm /home/{username}/temp/*
(Where you insert your username where appropriate.)
Special Note: While system commands are normally located in the same directories with standard settings for almost all machines, it is best to put the full path of the directory to any commands, system or not. For example, it would be better to use /usr/bin/rm instead of just rm. This also applies to any scripts. If there are not full paths to system commands (or other local commands), then it is possible that the cronjob will error. It is always best to include full path names on all commands.
Only command lines, blank lines and comments may be place in a crontab file. Any other type of text will cause the crontab to not function properly.
Now what?
Once the file is saved, the crontab is running. You do not need to initialize, or run any start-up program. Crontab executes when there is/are a command(s) (not comments or blank space) in the setup file (the one created above). If at any time you wish for command in the crontab file to not run anymore, just delete (or comment out) the line containing the command. If you wish to have no crontab jobs running at all, just remove (or comment out) all of the lines containing commands. (To add comments place # before any text.).
Why do I keep getting an email each time my Cron job runs?
The email is crontab's way of notifing you that it has completed (or not) the job you requested it to run. After everything is running smoothly, you may want to disable this feature, or redirect the output to a log file instaed of an email.
If you wish to diasble the email (and not output to a log file) then, at the end of each of the cron job lines you wish to not be notified on, place the command:
>/dev/null 2>&1
This essential writes the email out to nowhere (a trash bin of sorts), and thus solves the problem. Your final cron job line will look like this:
45 4 * * * rm /home/{username}/temp/* >/dev/null 2>&1
If you wish to diasble the email (and output to a log file) then, at the end of each of the cron job lines you wish to not be notified on, place the command:
> {logfile path and name}
or
>> {logfile path and name}
Special Note: One > means replace the current log with a new one, while (two) >> means append the current output to the end of the current log.
This essential writes the email out to nowhere (a trash bin of sorts), and thus solves the problem. Your final cron job line will look like this:
45 4 * * * rm /home/{username}/temp/* > /home/{username}/cronlogs/clear_temp_dir.txt >/dev/null 2>&1

 
Awesome Cron Job Examples
An experienced Linux sysadmin knows the importance of running the routine maintenance jobs in the background automatically.

Linux Cron utility is an effective way to schedule a routine background job at a specific time and/or day on an on-going basis.

 
Linux Crontab Format
 MIN HOUR DOM MON DOW CMD
Table: Crontab Fields and Allowed Ranges (Linux Crontab Syntax)

Field
Description
Allowed Value
MIN
Minute field
0 to 59
HOUR
Hour field
0 to 23
DOM
Day of Month
1-31
MON
Month field
1-12
DOW
Day Of Week
0-6
CMD
Command
Any command to be executed.
1. Scheduling a Job For a Specific Time Every Day
The basic usage of cron is to execute a job in a specific time as shown below. This will execute the Full backup shell script (full-backup) on 10th June 08:30 AM.

Please note that the time field uses 24 hours format. So, for 8 AM use 8, and for 8 PM use 20.


30 08 10 06 * /home/shailesh/full-backup
  • 30 – 30th Minute
  • 08 – 08 AM
  • 10 – 10th Day
  • 06 – 6th Month (June)
  • * – Every day of the week
2. Schedule a Job For More Than One Instance (e.g. Twice a Day)
The following script take a incremental backup twice a day every day.

This example executes the specified incremental backup shell script (incremental-backup) at 11:00 and 16:00 on every day. The comma separated value in a field specifies that the command needs to be executed in all the mentioned time.


00 11,16 * * * /home/shailesh/bin/incremental-backup
  • 00 – 0th Minute (Top of the hour)
  • 11,16 – 11 AM and 4 PM
  • * – Every day
  • * – Every month
  • * – Every day of the week
3. Schedule a Job for Specific Range of Time (e.g. Only on Weekdays)
If you wanted a job to be scheduled for every hour with in a specific range of time then use the following.
Cron Job everyday during working hours
This example checks the status of the database everyday (including weekends) during the working hours 9 a.m – 6 p.m


00 09-18 * * * /home/shailesh/bin/check-db-status
  • 00 – 0th Minute (Top of the hour)
  • 09-18 – 9 am, 10 am,11 am, 12 am, 1 pm, 2 pm, 3 pm, 4 pm, 5 pm, 6 pm
  • * – Every day
  • * – Every month
  • * – Every day of the week
Cron Job every weekday during working hours
This example checks the status of the database every weekday (i.e excluding Sat and Sun) during the working hours 9 a.m – 6 p.m.


00 09-18 * * 1-5 /home/shailesh/bin/check-db-status
  • 00 – 0th Minute (Top of the hour)
  • 09-18 – 9 am, 10 am,11 am, 12 am, 1 pm, 2 pm, 3 pm, 4 pm, 5 pm, 6 pm
  • * – Every day
  • * – Every month
  • 1-5 -Mon, Tue, Wed, Thu and Fri (Every Weekday)
4. How to View Crontab Entries?
View Current Logged-In User’s Crontab entries
To view your crontab entries type crontab -l from your unix account as shown below.


shailesh@dev-db$ crontab -l
@yearly /home/shailesh/annual-maintenance
*/10 * * * * /home/shailesh/check-disk-space

[Note: This displays crontab of the current logged in user]
View Root Crontab entries
Login as root user (su – root) and do crontab -l as shown below.


root@dev-db# crontab -l
no crontab for root
Crontab HowTo: View Other Linux User’s Crontabs entries
To view crontab entries of other Linux users, login to root and use -u {username} -l as shown below.


root@dev-db# crontab -u sathiya -l
@monthly /home/sathiya/monthly-backup
00 09-18 * * * /home/sathiya/check-db-status
5. How to Edit Crontab Entries?
Edit Current Logged-In User’s Crontab entries
To edit a crontab entries, use crontab -e as shown below. By default this will edit the current logged-in users crontab.


shailesh@dev-db$ crontab -e
@yearly /home/shailesh/centos/bin/annual-maintenance
*/10 * * * * /home/shailesh/debian/bin/check-disk-space
~
"/tmp/crontab.XXXXyjWkHw" 2L, 83C

[Note: This will open the crontab file in Vim editor for editing.
Please note cron created a temporary /tmp/crontab.XX... ]
When you save the above temporary file with :wq, it will save the crontab and display the following message indicating the crontab is successfully modified.


~
"crontab.XXXXyjWkHw" 2L, 83C written
crontab: installing new crontab
Edit Root Crontab entries
Login as root user (su – root) and do crontab -e as shown below.


root@dev-db# crontab -e
Edit Other Linux User’s Crontab File entries
To edit crontab entries of other Linux users, login to root and use -u {username} -e as shown below.


root@dev-db# crontab -u sathiya -e
@monthly /home/sathiya/fedora/bin/monthly-backup
00 09-18 * * * /home/sathiya/ubuntu/bin/check-db-status
~
~
~
"/tmp/crontab.XXXXyjWkHw" 2L, 83C
6. Schedule a Job for Every Minute Using Cron.
Ideally you may not have a requirement to schedule a job every minute. But understanding this example will will help you understand the other examples mentioned below in this article.

* * * * * CMD
The * means all the possible unit — i.e every minute of every hour through out the year. More than using this * directly, you will find it very useful in the following cases.
  • When you specify */5 in minute field means every 5 minutes.
  • When you specify 0-10/2 in minute field mean every 2 minutes in the first 10 minute.
  • Thus the above convention can be used for all the other 4 fields.
7. Schedule a Background Cron Job For Every 10 Minutes.
Use the following, if you want to check the disk space every 10 minutes.

*/10 * * * * /home/shailesh/check-disk-space
It executes the specified command check-disk-space every 10 minutes through out the year. But you may have a requirement of executing the command only during office hours or vice versa. The above examples shows how to do those things.

Instead of specifying values in the 5 fields, we can specify it using a single keyword as mentioned below.

There are special cases in which instead of the above 5 fields you can use @ followed by a keyword — such as reboot, midnight, yearly, hourly.
Table: Cron special keywords and its meaning
Keyword
Equivalent
@yearly
0 0 1 1 *
@daily
0 0 * * *
@hourly
0 * * * *
@reboot
Run at startup.
8. Schedule a Job For First Minute of Every Year using @yearly
If you want a job to be executed on the first minute of every year, then you can use the @yearly cron keyword as shown below.

This will execute the system annual maintenance using annual-maintenance shell script at 00:00 on Jan 1st for every year.
  
@yearly /home/shailesh/red-hat/bin/annual-maintenance
9. Schedule a Cron Job Beginning of Every Month using @monthly
It is as similar as the @yearly as above. But executes the command monthly once using @monthly cron keyword.

This will execute the shell script tape-backup at 00:00 on 1st of every month.

@monthly /home/shailesh/suse/bin/tape-backup
10. Schedule a Background Job Every Day using @daily
Using the @daily cron keyword, this will do a daily log file cleanup using cleanup-logs shell scriptat 00:00 on every day.

@daily /home/shailesh/arch-linux/bin/cleanup-logs "day started"
11. How to Execute a Linux Command After Every Reboot using @reboot?
Using the @reboot cron keyword, this will execute the specified command once after the machine got booted every time.

@reboot CMD
12. How to Disable/Redirect the Crontab Mail Output using MAIL keyword?
By default crontab sends the job output to the user who scheduled the job. If you want to redirect the output to a specific user, add or update the MAIL variable in the crontab as shown below.


shailesh@dev-db$ crontab -l
MAIL="shailesh"

@yearly /home/shailesh/annual-maintenance
*/10 * * * * /home/shailesh/check-disk-space

[Note: Crontab of the current logged in user with MAIL variable]

If you wanted the mail not to be sent to anywhere, i.e to stop the crontab output to be emailed, add or update the MAIL variable in the crontab as shown below.


MAIL=""
13. How to Execute a Linux Cron Jobs Every Second Using Crontab.
You cannot schedule a every-second cronjob. Because in cron the minimum unit you can specify is minute. In a typical scenario, there is no reason for most of us to run any job every second in the system.

 
14. Specify PATH Variable in the Crontab
All the above examples we specified absolute path of the Linux command or the shell-script that needs to be executed.

For example, instead of specifying /home/shailesh/tape-backup, if you want to just specify tape-backup, then add the path /home/shailesh to the PATH variable in the crontab as shown below.


shailesh@dev-db$ crontab -l

PATH=/bin:/sbin:/usr/bin:/usr/sbin:/home/shailesh

@yearly annual-maintenance
*/10 * * * * check-disk-space

[Note: Crontab of the current logged in user with PATH variable]
15. Installing Crontab From a Cron File
Instead of directly editing the crontab file, you can also add all the entries to a cron-file first. Once you have all thoese entries in the file, you can upload or install them to the cron as shown below.


shailesh@dev-db$ crontab -l
no crontab for shailesh

$ cat cron-file.txt
@yearly /home/shailesh/annual-maintenance
*/10 * * * * /home/shailesh/check-disk-space

shailesh@dev-db$ crontab cron-file.txt

shailesh@dev-db$ crontab -l
@yearly /home/shailesh/annual-maintenance
*/10 * * * * /home/shailesh/check-disk-space
Note: This will install the cron-file.txt to your crontab, which will also remove your old cron entries. So, please be careful while uploading cron entries from a cron-file.txt.
Cron Vs Anacron: How to Setup Anacron on Linux (With an Example)
Anacron is the cron for desktops and laptops.
Anacron does not expect the system to be running 24 x 7 like a server.
When you want a background job to be executed automatically on a machine that is not running 24 x 7, you should use anacron.
For example, if you have a backup script scheduled everyday at 11 PM as a regular cron job, and if your laptop is not up at 11 PM, your backup job will not be executed.
However, if you have the same job scheduled in anacron, you can be sure that it will be executed once the laptop come back up.
Anacrontab Format
Just like how cron has /etc/crontab, anacron has /etc/anacrontab.
/etc/anacrontab file has the anacron jobs mentioned in the following format.


period   delay   job-identifier   command
Field 1 is Recurrence period: This is a numeric value that specifies the number of days.
  • 1 – daily
  • 7 – weekly
  • 30 – monthly
  • N – This can be any numeric value. N indicates number of days
Note: You can also use ‘@monthly’ for a job that needs to be executed monthly.
Field 2 is Delay: This indicates the delay in minutes. i.e X number of minutes anacron should wait before executing the job after the the machine starts.
Field 3 is Job identifier: It is the name for the job’s timestamp file. It should be unique for each job. This will be available as a file under the /var/spool/anacron directory. This file will contain a single line that indicates the last time when this job was executed.


# ls -1 /var/spool/anacron/
test.daily
cron.daily
cron.monthly
cron.weekly

# cat /var/spool/anacron/test.daily
20110507
Field 4 is command: Command or shell script that needs to be executed.
Just like shell scripts, comments inside anacrontab file starts with #
Note: For /etc/crontab file format, refer to our Linux Crontab: 15 Awesome Cron Job Examples article.
Anacron Example
The following example executes the /home/sathiya/backup.sh script once in every 7 days.
On the day when the backup.sh job is supposed to executed, if the system is down for some reason, anacron will execute the backup.sh script 15 minutes after the system comes back up (without having to wait for another 7 days).


# cat /etc/anacrontab
7       15      test.daily      /bin/sh /home/sathiya/backup.sh
START_HOURS_RANGE and RANDOM_DELAY
The above example indicates that the backup.sh script should be executed every day, with a delay of 15 mins. i.e When the laptop was started, executed it only after 15 minutes.
What happens when the laptop or desktop was not shutdown? When does the job gets executed? This is specified by the START_HOURS_RANGE environment variable in the /etc/anacrontab file.
By default this is set to 3-22 in the file. This indicates the time range from 3 a.m to 10 p.m.


# grep START /etc/anacrontab
START_HOURS_RANGE=3-22
On top of the user defined delay specified in the 2nd field of the /etc/anacrontab file, anacron also randomly adds x number of minutes. The x is defined by the RANDOM_DELAY variable in the /etc/anacrontab file.
By default this is set to 45 in the file. This means that anacron will add x minutes (randomly picked from 0 and 45), and add this to the user defined delay.


# grep RANDOM /etc/anacrontab
RANDOM_DELAY=45
Cron Vs Anacron
Cron and anacron has its own advantages and disadvantages. Depending on your requirement, use one of them.
Cron
Anacron
Minimum granularity is minute (i.e Jobs can be scheduled to be executed every minute)
Minimum granularity is only in days
Cron job can be scheduled by any normal user ( if not restricted by super user )
Anacron can be used only by super user ( but there are workarounds to make it usable by normal user )
Cron expects system to be running 24 x 7. If a job is scheduled, and system is down during that time, job is not executed.
Anacron doesn’t expect system to be running 24 x 7. If a job is scheduled, and system is down during that time, it start the jobs when the system comes back up.
Ideal for servers
Ideal for desktops and laptops
Use cron when a job has to be executed at a particular hour and minute
Use anacron when a job has to be executed irrespective of hour and minute

 
Do You Make These Cron Job Mistakes?
Question: Why my cron job does not get executed at the specified time ?

Answer: There may be lot of reasons why a cron job may not get executed. Let us review 5 important reasons of why a cron job does not run at the specified time and how to resolve those issues.
1. Misinterpretation of Time Field and Specifying Wrong Values.
Misinterpretation of the time field, and given values in the time field which does not mentions the expected/intended time.
For example, to execute a command at 8 PM, you should specify the time in 24 hour format. i.e 8 PM is 20 and not 8 as shown below.


0 8 * * * /home/ubuntu/full-backup
[Note: The is wrong for 8 p.m]
0 20 * * * /home/ubuntu/full-backup
[Note: This is correct for 8 p.m]
Read our tutorial Linux Crontab: 15 Awesome Cron Job Examples to get a deep understanding on crontab. One of our regular reader Binny has created a web interface which will generate cron entries when you select appropriate values for various crontab fields in the user interface.
2. Invalid Path to Shell Script or Commands in crontab
Make sure the full path to the shell script is specified in the crontab.


0 8 * * * tape-backup
[Note: Invalid. No full path specified]

0 8 * * * /home/debian-os/bin/tape-backup
[Note: Valid. This is correct with full path]
Note: If you don’t want to give full path in the crontab, make sure to add PATH variable in crontab (example #14)
3. No Execute Permission For the Shell Script in Cron
You might have given the correct command with correct path, but the command might not have execute permission. If you are using any Unix standard commands then it will be having the execute permission set by default.
But, if you are using some user defined commands (shell scripts), make sure to give execute permission to it as shown below.


*/15 * * * * /home/fedora-os/check-disk-space
[Note: Executes check-disk-space every 15 minutes]

# cd /home/fedora-os
# chmod u+x check-disk-space
4. %age in Cron Job Command or Shell Script
If a command has a % in it, your command will not get executed. Refer our previous Crontab %age Issue FAQ to understand how to fix this issue.
5. Disallowed to Execute Cron Job By Sysadmin
A system administrator can decide which user can run cron jobs and which users cannot. So to deny a user from executing a cron job, sysadmin might have placed your username in the /etc/cron.deny file.

If you have root privilege, check the /etc/cron.deny file to make sure your name is not listed in there. If it is listed, edit the file and remove your name. If you don’t have root privilege contact your sysadmin.

 
Crontab Issue: Cron Job is Not Working When Using Percentage

 
Question: What is the reason my cron job does not gets executed when i use percentage ‘%’ in my cron job. How to solve this issue ?

Answer:‘%’ is the new line specifier in cron command. Thus when you use % it is interpreted as a new line in the cron job. Let us see how to over come this issue, and use % in the cron job.
Problem Definition With Example: ‘%’ in the cron job ( non successful cron job )


* * * * * date +"%d" >> /tmp/non-working-ex1.txt

For testing purpose all fields in the above crontab example has * in it. This will execute the specified cronjob every minute.

To understand the crontab configuration, read our earlier article that contains 15 awesome cron job examples.

If you have access to syslog you will a similar line like the following.


Jun 20 08:31:01 ubuntu-laptop /USR/SBIN/CRON[6752]: (shailesh) CMD (date +")

In the syslog entry for this specific example the command is show only as: (date +”). Ideally this should be displayed as: date +”%d” . This indicates that the percentage is parsed as a special symbol in the cron. i.e it terminates the command exactly at the %age.
Solution With Example: Work around to use ‘%’ in the cron job.
You can solve this problem using the following two methods. This solution should solve the problem on all flavors of Unix / Linux, including Ubuntu, Debian, Fedora, RedHat, CentOS, AIX etc.,
Method 1: Escaping the percentage with \
You can escape the percentage with backslash, and make it working as a normal job.


$ crontab -l
* * * * * date +"\%M" > /tmp/working-ex1.txt

Note: This ‘\’ will not be seen by date command, or any other command you invoke. The \ is to escape the special behavior of percentage in cron.
Method 2: Use Shell Script
Create a shell script with the percentage command and schedule the shell script as cron job.


$ cat /bin/date.sh
date +"%d"

$ crontab -l
* * * * * /bin/sh /bin/date.sh > /tmp/working-ex2.txt
At the next minute you will be having the executed command output in the /tmp/working-ex2.txt

Now you will have the following line which executed the command successfully in the syslog.


Jun 20 08:36:01 ubuntu-laptop /USR/SBIN/CRON[6962]: (shailesh) CMD (/bin/sh /bin/date.sh >> /tmp/working-ex2.txt)

Note: Don’t forget to remove these testing cron entries as it will get executed every minute.
What is Cron?

Q . Can you explain what is Cron? Why I need cron?

A. Cron is UNIX/Linux service or daemon to execute scheduled commands. It is also known as the clock daemon that executes commands at specified dates and times according to instructions in a file. Generally, crontab uses a daemon, crond, which runs constantly in the background and checks once a minute to see if any of the scheduled jobs need to be executed. If so, it executes them. These jobs are generally referred to as cron jobs. Cron is controlled by a set of files called "crontabs". There is the master file in /etc/crontab. Each users cronjob is stored in /var/spool/cron/username directory.

Editing Crontab or setting up your own job Just type following command:

$ crontab -e

Run crontab Every 10 Minutes

Q. How do I run a cron job or a shell script every 10 minutes using Linux / UNIX cron
service?

A. cron [2] is a time-based scheduling service in Linux / Unix-like computer operating
systems.

Login to UNIX system

Type the following command to enter cronjob:
$ crontab -e

Each cronjob has following syntax:
# +---------------- minute (0 - 59)
# | +------------- hour (0 - 23)
# | | +---------- day of month (1 - 31)
# | | | +------- month (1 - 12)
# | | | | +---- day of week (0 - 6) (Sunday=0 or 7)
# | | | | |
* * * * * command to be executed

To get crontab to run a task every 10 minutes you could type as follow

*/10 * * * * /path/to/command
Save and close the file.

Linux Verify crond Daemon And Cronjobs Are Running

Q. How do I verify or check cronjob is running or not under CentOS / RHEL / Fedora Linux from a shell prompt?

A. cron / crond is daemon to execute scheduled commands (Vixie Cron). Usually, it is started automatically from /etc/init.d on entering multi-user
runlevels. RHEL / CentOS / Fedora Linux Verify Cron Service You can simply use any one of the following command to see if crond is running or not, enter:

# pgrep crond
OR
# service crond status

Sample output:
crond (pid 4370) is running...

If it is not running type the following two command to start crond:
# chkconfig crond on
# service crond start

Verify cron is running by viewing log file, enter:
# tail -f /var/log/cron

A note about Debian / Ubuntu Linux Cron service Under Debian and Ububtu Linux cron logs its action logged to the syslog facility i.e. use /var/log/messages file:
# tail -f /var/log/messages

Find out if cron daemon is running or not, enter:
# pgrep cron

Linux / UNIX Crontab File Location

I login to my UNIX system as a normal user. However, I need to update my cronjob entry. But, I can't find where the crontab file is. How do I find out my crontab file location?
By default cron searches its spool area /var/spool/cron/crontabs directory for crontab files. All files which are named after username i.e. accounts in /etc/passwd file. So if your username is vivek, crontab file location should be /var/spool/cron/crontabs/$USER

i.e. /var/spool/cron/crontabs/vivek. Note that crontabs in this directory should not be accessed directly - the crontab command should be used to access and update them as follows:

crontab -e

To view your crontab file (cron jobs) type

crontab -l

Linux / UNIX: Change Crontab Email Settings ( MAILTO )

Q. I'd like to send email to user@example.com instead of default root user. How do I change email settings under crontab file [2]?

A. A crontab file contains [2] instructions to the cron daemon. An active line in a crontab will be either an environment setting or a cron command. An
environment setting is of the form:

name = value

where the spaces around the equal-sign (=) are optional, and any subsequent non-leading spaces in value will be part of the value assigned to name. The value string may be placed in quotes (single or double, but matching) to preserve leading or trailing blanks. The value string is not parsed for environmental substitutions, thus lines like

PATH = $HOME/bin:$PATH

will not work as you might expect.

MAILTO Variable

In addition to LOGNAME, HOME, and SHELL, cron will look at MAILTO if it has any reason to send mail as a result of running commands in "this" crontab. If MAILTO is defined (and non-empty), mail is sent to the user so named. First open your crontab file:

# vi /etc/crontab
OR
$ crontab -e

To send email to vivek@nixcraft.in, enter:

MAILTO=vivek@nixcraft.in

If MAILTO is defined but empty (MAILTO=""), no mail will be sent.

MAILTO=""

Otherwise mail is sent to the owner of the crontab.

Linux Execute Cron Job After System Reboot

I am on Red Hat Enterprise Linux 5.x server. Is there is an easy way to run script or command at boot time after fresh reboot command [2]?
crontab is the program used to install, deinstall or list the tables used to drive the cron daemon in Vixie Cron. Each user can have their own crontab, and though these are files in /var/spool/cron/crontabs, they are not intended to be edited directly. You or user can use crontab program to edit cron jobs. Running job at statup (boot)

You need to use special string called @reboot. It will run once, at startup after reboot command.

@reboot /path/to/job
@reboot /path/to/shell.script
@reboot /path/to/command

This is an easy way to give your users the ability to run a shell script or command at boot time without root access. First, run crontab command:

$ crontab -e
OR
# crontab -e -u UserName
# crontab -e -u vivek

Run a script called /home/vivek/bin/installnetkit.sh

@reboot /home/vivek/bin/installnetkit.sh

You also need to enable crond service via sys v / BSD init style system. Under RHEL / CentOS / Fedora, you need to use chkconfig (ntsysv) command [3] to enable crond on boot:
# chekconfg crond on

Under Debian / Ubuntu Linux use update-rc.d as follows to turn on service on boot [4]:
# update-rc.d cron defaults

Save and close the file.

Linux / UNIX Restrict at / cron Usage To Authorized Users

The cron and at services [2] are used to allow commands to be executed at a later time. How do I restrict them to selected users such as root, opt1, opt2 and so on? How do I make sure user php can run php script but cannot modify or install a new job?
The cron service is required by almost all UNIX / Linux / BSD oses to perform necessary maintenance tasks. Both cron and anacron make use of a number of configuration files and directories. Regular users can modify and install their own cron configuration or jobs.

1. /etc/cron.allow - Put users who are allowed to use cron.
2. /etc/at.allow - Put users who are allowed to use at.

If these files exist and if the corresponding files /etc/cron.deny and /etc/at.deny do not exist, then only users listed in the relevant allow files can run the crontab and at commands to submit their jobs.

How Do I Restrict at And cron To Authorized Users Only?

First, delete both /etc/cron.deny and /etc/at.deny files.
# rm /etc/cron.deny /etc/at.deny

Now, open /etc/cron.allow, enter:
# vi /etc/cron.allow

Add one line for each user allowed to use the crontab command to create cron jobs. Finally, edit /etc/at.allow using a text editor such as vi, enter:
# vi /etc/at.allow

Add one line for each user allowed to use the at command to create at jobs:
vivek
shri
krish
tom
root
foo
bar
php

Note that even if a user called jerry is not listed in cron.allow, cron jobs, he can still be run as that user. The cron.allow file controls only administrative access to the crontab command for scheduling and modifying cron jobs. In other words you can set / modify cron jobs on behalf of jerry. Jerry can only run it but cannot set or modify jobs.

Q . How do I add cron job under Linux or UNIX like operating system?

A. Cron [2] job are used to schedule commands to be executed periodically i.e. to setup commands which will repeatedly run at a set time, you can use the cron jobs.
crontab is the command used to install, deinstall or list the tables used to drive the cron daemon in Vixie Cron. Each user can have their own crontab, and though these are files in /var/spool/cron/crontabs, they are not intended to be edited directly. You need to use crontab command for editing or setting up your own cron jobs.

To edit your crontab file, type the following command:
$ crontab -e
Syntax of crontab
Your cron job looks like as follows:

1 2 3 4 5 /path/to/command arg1 arg2

Where,
1: Minute (0-59)
2: Hours (0-23)
3: Day (0-31)
4: Month (0-12 [12 == December])
5: Day of the week(0-7 [7 or 0 == sunday])
/path/to/command - Script or command name to schedule
Same above five fields structure can be easily remembered with following diagram:

* * * * * command to be executed
- - - - -
| | | | |
| | | | ----- Day of week (0 - 7) (Sunday=0 or 7)
| | | ------- Month (1 - 12)
| | --------- Day of month (1 - 31)
| ----------- Hour (0 - 23)
------------- Minute (0 - 59)

Example(s)
If you wished to have a script named /root/backup.sh run every day at 3am, my crontab entry would look like as follows:

(a) Install your cronjob:
# crontab -e

(b)Append following entry:
0 3 * * * /root/backup.sh

Run five minutes after midnight, every day:
5 0 * * * /path/to/command

Run at 2:15pm on the first of every month:
15 14 1 * * /path/to/command

Run at 10 pm on weekdays:
0 22 * * 1-5 /path/to/command

Syntax of crontab 2/5
Run 23 minutes after midnigbt, 2am, 4am ..., everyday:
23 0-23/2 * * * /path/to/command

Run at 5 after 4 every sunday:
5 4 * * sun /path/to/command

Use of operators
An operator allows you to specifying multiple values in a field. There are three operators:

1. The asterisk (*) : This operator specifies all possible values for a field. For example, an asterisk in the hour time
field would be equivalent to every hour or an asterisk in the month field would be equivalent to every month.

2. The comma (,) : This operator specifies a list of values, for example: "1,5,10,15,20, 25".

3. The dash (-) : This operator specifies a range of values, for example: "5-15" days , which is equivalent to typing
"5,6,7,8,9,....,13,14,15" using the comma operator.

How do I disabling Email output?
By default the output of a command or a script (if any produced), will be email to your local email account. To stop receiving email output from crontab you need to append >/dev/null 2>&1. For example:
0 3 * * * /root/backup.sh >/dev/null 2>&1

To mail output to particluer email account let us say vivek@nixcraft.in you need to define MAILTO variable to your cron job:
MAILTO="vivek@nixcraft.in"
0 3 * * * /root/backup.sh >/dev/null 2>&1

Task:To list your crontab jobs use the command
Type the following command:
# crontab -l

To remove or erase all crontab jobs use the command:
# crontab -r

Use special string to save time Instead of the first five fields, you can use any one of eight special strings. It will not just save your time but it will improve readability.

Special string Meaning
@reboot Run once, at startup.
@yearly Run once a year, "0 0 1 1 *".
@annually (same as @yearly)
@monthly Run once a month, "0 0 1 * *".
@weekly Run once a week, "0 0 * * 0".
@daily Run once a day, "0 0 * * *".
@midnight (same as @daily)
@hourly Run once an hour, "0 * * * *".

Run ntpdate every hour:
@hourly /path/to/ntpdate

Make a backup everyday:
@daily /path/to/backup/script.sh

Use special string to save time 3/5

Understanding /etc/crontab file and /etc/cron.d/* directories
/etc/crontab is system crontabs file. Usually only used by root user or daemons to configure system wide jobs. All individual user must must use crontab command to install and edit their jobs as described above. /var/spool/cron/ or /var/cron/tabs/ is directory for personal user crontab files. It must be backup with users home directory.

Typical /etc/crontab file entries:
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
HOME=/

# run-parts
01 * * * * root run-parts /etc/cron.hourly
02 4 * * * root run-parts /etc/cron.daily
22 4 * * 0 root run-parts /etc/cron.weekly
42 4 1 * * root run-parts /etc/cron.monthly

Additionally, cron reads the files in /etc/cron.d/ directory. Usually system daemon such as sa-update or sysstat places their cronjob here. As a root user or superuser you can use following directories to configure cronjobs. You can directly drop your scripts here. run-parts command run scripts or programs in a directory via /etc/crontab
Directory Description
/etc/cron.d/ Put all scripts here and call them from /etc/crontab file.
/etc/cron.daily/ Run all scripts once a day
/etc/cron.hourly/ Run all scripts once an hour
/etc/cron.monthly/ Run all scripts once a month
/etc/cron.weekly/ Run all scripts once a week

How do I use above directories to put scripts?
Here is a sample shell script (clean.cache) to clean up cached files every 10 days. This script is directly created at /etc/cron.daliy/ directory i.e. create a file called /etc/cron.daily/clean.cache:
#!/bin/bash
CROOT="/tmp/cachelighttpd/"
DAYS=10
LUSER="lighttpd"
LGROUP="lighttpd"
# start cleaning
/usr/bin/find ${CROOT} -type f -mtime +${DAYS} | xargs -r /bin/rm
# if directory deleted by some other script just get it back
if [ ! -d $CROOT ]
then
/bin/mkdir -p $CROOT
/bin/chown ${LUSER}:${LGROUP} ${CROOT}
fi

Disable The Mail Alert By Crontab Command

How do I to disable the mail alert send by crontab? When my job is executed and the jobs cannot run normally it will sent an email to root. Why do I receive e-mails to my root
account from cron? How can I prevent this?

crontab command is use to maintain crontab files for individual users. By default the output of a command or a script (if any produced), will be email to your local email account. To stop receiving email output from crontab you need to append following string: Cron Job Prevent the sending of errors and output

To prevent the sending of errors and output, add any one of the following at the end of the line for each cron job to redirect output to /dev/null.

>/dev/null 2>&1.
OR
&> /dev/null

Cron Job Example Edit/Open your cron jobs, enter:
$ crontab -e

Append string >/dev/null 2>&1 to stop mail alert:
0 1 5 10 * /path/to/script.sh >/dev/null 2>&1
OR
0 1 5 10 * /path/to/script.sh &> /dev/null

Save and close the file. Restart the crond:

# /etc/init.d/crond restart

MAILTO variable
As pointed out by Anand Sharma, you can set MAILTO="" variable at the start of your crontab file. This will also disable email. Edit/Open your cron jobs
$ crontab -e

At the top of the file, enter:
MAILTO=""

Save and close the file.

 
Issue1:How to deny a user not to use his/her crontab to schedule his jobs
there is seperate contab file for dening for user open and file and specify users name in that file
#vi /etc/cron.deny
Issue2:Display cron jobs for all users
When migrating from one system to another it is good to know if there are cron jobs from other users on the system, here is how to display all of them:
1. for i in `cat /etc/passwd | cut -f 1 -d ':'`; do crontab -u $i -l; done;
or
for user in $(cut -f1 -d: /etc/passwd); do crontab -u $user -l; done
will loop over each user name listing out their crontab. The crontabs are owned by the respective users so you won't be able to see another user's crontab w/o being them or root.
ISSUE3:Using crontab as alaram? I want a song played on every weekday at 5AM and i dont want it in weekends
here is the solution you requred mplayer or vlc player to do this which will support CLI execution.
mplayer /music.mp3 & /dev/null&
00 05 * * 1-5 mplayer /music.mp3 & /dev/null&
ISSUE4:I have written a shell script that works from console but does not work via crontab.
This type of issues will occure in four situations
1. when there is some env variable issue
2. when crontab service it self not running in your system
check wether crontab service is running or not
#pgrep cron
3. When there is some issue with cron job contents(like check for spaces and empty lines remove all of them) 
if you didnt find any cron process running please start the crontab service as below
#service crond restart
4. when you are executing script or command please specify the full path to that command
ISSUE5:I am running a script , working very fine on cmd prompt. The problem is that when I open do crontab -e its giving some weired values like below 
baafh-99.03#
baafh-99.03# crontab -e
1063

?

?

?

?

?
how to resolve this issue?

This type of issue will come when the default editor is not set to VI to do this just execute the below commands

EDITOR=vi;
export EDITOR

Some important files and command for crontab
/var/cron/log file is used for logging some crontab messages, so very much useful for debugging crontab issue
/etc/crontab is the main configuration file for crontab where you can see crontab settings and all crontab hourly,monthly etc folders in this file
/etc/cron.hourly
/etc/cron.dialy
/etc/cron.weekly
/etc/cron.monthly these folders are used for keeping scripts in this folders so that on that perticular day/time the script will execute.

 
How to run a crontab entry as "nobody"

 
Here's a quick example of how to run a program on a Linux system through a crontab entry, with the program being executed as the user nobody.

Just put this entry in a crontab file (by issuing the "crontab -e" command, for example), and the program named myProgram.sh will be run at 1:30 a.m. using the Bourne shell, and will be run as the user nobody.

30 1 * * * su -c '/path/to/program/myProgram.sh' -s /bin/sh nobody

Of course testing is always recommended, but this has worked for me.