SoFunction
Updated on 2025-03-10

Detailed explanation of the Crontab commands in Unix/Linux

Introduction

The crontab command is commonly found in Unix and Unix-like operating systems and is used to set instructions that are executed periodically. This command reads instructions from the standard input device and stores them in a "crontab" file for later reading and execution.

Usually, the instructions stored in crontab are activated by the daemon, and crond is often run in the background, checking every minute whether there are scheduled jobs to be executed. This type of job is generally called cron jobs.

cron is a service in Unix/Linux that provides regular execution of shell commands, including two parts: crond and crontab:

crond: The daemon of the cron service, the resident memory is responsible for regular scheduling

crontab: cron's management tool, responsible for editing the scheduling plan

The following demonstration is performed under Ubuntu 16.04. The basic usage method can be done by commandsman crontab Check

NAME
  crontab - maintain crontab files for individual users (Vixie Cron)

SYNOPSIS
  crontab [ -u user ] file
  crontab [ -u user ] [ -i ] { -e | -l | -r }

A brief explanation

    -eEdit, similar to vim, the syntax will be checked when saving and exiting

    -l List all tasks

    -rDelete all tasks

If crontab runs error, you can view the log file /var/log/syslog

Basic syntax

The syntax of cron is very simple, divided into six major blocks, of which the first five blocks are used to specify the time period, and the last block is the specific commands executed, which looks like this format:

min hour day month week command

in

    min Indicates minutes, range 0-59

    hour Indicates hours, range 0-23

    day Indicates days, range 1-31

You can fill in L to indicate the last day of the month

You can fill in W, 1W indicates the closest working day to No. 1

    month Represents month, range 1-12

The last day of each month crontab itself is not supported and needs to be judged through scripts.

    week Represent week, range 0-7

Here, 0 and 7 represent Sunday

Week and sun and moon cannot coexist, and may conflict

You can fill in #, 4#3 to indicate the third Thursday of the month

You can fill in L, 5L to indicate the last Friday of the month

    command Indicates the specific command to be executed (preferably the absolute path)

If there are multiple commands, you need to use & to connect, or write multiple commands in a shell script, and then crontab executes the shell script regularly.

In addition, similar to regular expressions, there are some special symbols to help us achieve flexible scheduling

    *Asterisk, indicating that every possible value is accepted

For example * * * * * command means that command is executed once every minute

    , Comma, parallel time

For example * 6,12,18 * * * command means that command is executed once at 6, 12 and 18 points

    - Minus sign, continuous interval

For example * 9-17 * * * command means that command is executed every minute from 9 o'clock to 17 o'clock

    /Slash, interval unit

For example */5 * * * * command means that command is executed every 5 minutes

System level Crontab

If we need to execute some instructions with higher permissions, we need to use root permissions to execute. The mechanism at this time is also different from the basic syntax introduced above. The file we need to edit is /etc/crontab. Let's take a look at its content first

dawang@dawang-Parallels-Virtual-Platform:~$ cat /etc/crontab
# /etc/crontab: system-wide crontab
# Unlike any other crontab you don't have to run the `crontab'
# command to install the new version when you edit this file
# and files in /etc/. These files also have username fields,
# that none of the other crontabs do.

SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

# m h dom mon dow user command
17 * * * * root cd / && run-parts --report /etc/
25 6 * * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/ )
47 6 * * 7 root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/ )
52 6 1 * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/ )
#

We need to add command executors between commands and time intervals, and we can also add environment variables to use in scheduling. We see several cron.* files in the configuration file. Let's first see what other similar files are there

dawang@dawang-Parallels-Virtual-Platform:~$ ll /etc | grep cron
-rw-r--r-- 1 root root  401 12moon 29 2014 anacrontab
drwxr-xr-x 2 root root 4096 4moon 21 06:14 /
drwxr-xr-x 2 root root 4096 4moon 21 06:14 /
drwxr-xr-x 2 root root 4096 4moon 21 06:08 /
drwxr-xr-x 2 root root 4096 4moon 21 06:14 /
-rw-r--r-- 1 root root  722 4moon 6 05:59 crontab
drwxr-xr-x 2 root root 4096 4moon 21 06:14 /

in

    Directory: All files that comply with the scheduling syntax in this directory and in the subdirectories will be executed

    : Record users who refuse to execute

    : Record the user allowed to execute. This file has a high priority. Generally speaking, only one file is required (see whether it is a whitelist or a blacklist mechanism required)

    /hourly/monthly/weekly Directory: All scripts are executed at the specified time

For more detailed introduction, you can enterman 5 crontab orman 8 cron View

principle

Why do we use itcrontab -eEdit it and add a timed task? Every time we add a line, this work will be recorded in /var/spool/cron/crontab. If my username is dawang, the corresponding file is /var/spool/cron/crontab/dawang (requires root permission to view). However, it is not recommended to modify directly, because direct modification will not perform syntax checks.

In some systems, the source configuration file is not necessarily read every time (but it uses the version loaded into memory). At this time, we need to restart the crond service and the command is /sbin/service crond restart

Crond Service Management

By default, the system does not start the crond service for us. If you want to start the computer, you need to add the service crond start line in /etc//. The other management commands are

# Start the service/sbin/service crond start 
# Close the service/sbin/service crond stop 
# Restart the service/sbin/service crond restart 
# Reload the configuration/sbin/service crond reload

Example test

Let's go to the actual combat, the first time we use itcrontab -eWe need to choose the editor, the default is nano, but I chose vim

dawang@dawang-Parallels-Virtual-Platform:~$ crontab -e
no crontab for dawang - using an empty one

Select an editor. To change later, run 'select-editor'.
 1. /bin/ed
 2. /bin/nano  <---- easiest
 3. /usr/bin/

Choose 1-3 [2]:

To verify that it is really executing, we set up two operations that are performed every minute, as follows (mainly focusing on the last two lines):

# Edit this file to introduce tasks to be run by cron.
#
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for the task
#
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').#
# Notice that tasks will be started based on the cron's system
# daemon's notion of time and timezones.
#
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
#
# For example, you can run a backup of all your user accounts
# at 5  every week with:
# 0 5 * * 1 tar -zcf /var/backups/ /home/
#
# For more information see the manual pages of crontab(5) and cron(8)
#
# m h dom mon dow command
* * * * * date >> /home/dawang/
* * * * * echo "time to go!" >> /home/dawang/

Two things are done here, one is to report time per minute, and the other is to output a paragraph per minute. Here >> means additional output, and more input and output methods are introduced in the next section. If the service was not started just now, use it nowservice crond start Start, then wait for a while and you can see the output. Please refer to the following commands for details, so I won't go into details here:

dawang@dawang-Parallels-Virtual-Platform:~$ ll | grep txt
-rw-rw-r-- 1 dawang dawang 1849 7moon 26 16:08 
-rw-rw-r-- 1 dawang dawang 516 7moon 26 16:08 
dawang@dawang-Parallels-Virtual-Platform:~$ tail -n 10 
2016Year 07moon 26day Tuesday 16:01:01 CST
2016Year 07moon 26day Tuesday 16:02:01 CST
2016Year 07moon 26day Tuesday 16:03:01 CST
2016Year 07moon 26day Tuesday 16:04:01 CST
2016Year 07moon 26day Tuesday 16:05:01 CST
2016Year 07moon 26day Tuesday 16:06:01 CST
2016Year 07moon 26day Tuesday 16:07:01 CST
2016Year 07moon 26day Tuesday 16:08:01 CST
2016Year 07moon 26day Tuesday 16:09:01 CST
2016Year 07moon 26day Tuesday 16:10:01 CST
dawang@dawang-Parallels-Virtual-Platform:~$ tail -n 10  
time to go!
time to go!
time to go!
time to go!
time to go!
time to go!
time to go!
time to go!
time to go!
time to go!

Redirect command

Here is an example

command &gt; file Redirecting standard output to file
command &gt;&gt; file Append standard output to file
command 1 &gt; file Redirecting standard output to file
command 2 &gt; file Redirecting standard errors to file
command 2 &gt;&gt; file Append standard output to file
command 2&gt;&amp;1 BundlecommandCommand standard error redirects to standard output
command &gt; file 2&gt;&amp;1 Bundle标准输出和标准错误一起重定向到文件
command &gt;&gt; file 2&gt;&amp;1 Bundle标准输出和标准错误一起追加到文件
command &lt; file BundlecommandCommand tofileFiles as standard input
command &lt; file &gt;file2 BundlecommandCommand tofileFiles as standard input,byfile2Files as standard output
command &lt;&amp;- Close standard input

Summarize

The above is the entire content of this article. I hope it will be of some help to everyone's study or work.