You are on page 1of 83

CTEC

Introduction to Linux II
Topic 04
Recap

// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT 2


Overview

• This session explains the processes in Linux;


• It also introduces the vi Editor;
• And discusses pipes, filters and I/O redirection;
• And also introduces Crontab for job scheduling.

// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT 3


Objectives

• Understand processes in Linux;


• Demonstrate use of vi editor;
• Understand the workings of pipes and I/O redirection;
• Demonstrate how to schedule jobs with crontab.

// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT


LINUX PROCESSES
What are Processes?

• Processes in Linux start every time you launch an application or run a


command. While each command creates one process, applications
create and run multiple processes for different tasks.

// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT 6


What are Processes?

• There are 2 types of processes:

Foreground

Background

// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT 7


Foreground Processes

• By default, each new process


starts as a foreground process.
• It must finish before a new Foreground
process can begin.
• It requires the user to start
them or to interact with them.
i.e. it needs some input from the
keyboard and sends the output Background
to the screen

// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT 8


Foreground Processes

• E.g. the ls command. Here is an example to list all files in a directory


using an * as wild card:

• The above example displays all files where the name starts with
file and end with .txt.
// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT 9
Foreground Processes

• When the previous example process runs in the foreground, the


output is directed to the screen
• If the ls command wants any input (which it does not), it waits for it
from the keyboard.
• While a program is running in the foreground and is time-consuming,
no other commands can be run (ie. cannot start any other processes)
because the prompt would not be available until the program
finishes processing and appears.

// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT 10


Background Processes

• Running processes in
the background allows you to
perform other tasks at the same Foreground
time.
• If the background process
requires any keyboard input, it
waits.
Background

// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT 11


Background Processes

• The advantage of running a process in the background is that you


can run other commands; you do not have to wait until it completes
to start another.
• The simplest way to start a background process is to add an
ampersand (&) at the end of the command.

// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT 12


Background Processes

• Using the same example to list all files in a directory, the following
command is issued:
ls file*.txt &
• Here, if the ls command wants any input (which it does not), it goes
into a stop state until we move it into the foreground and give it the
data from the keyboard. At this point you will see a blinking cursor.

// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT 13


Background Processes

• The line “[1] 349” contains information about the background


process - the job number and the process ID.

// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT 14


Background Processes

• Press the Enter key and you will see the following:

• The new line indicates that the ls command background process


finishes successfully. A new prompt will then appear for another
command.

// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT 15


List Running Processes

• You can use the ps command to see the running processes.

// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT 16


List Running Processes

• One of the most commonly used flags for ps is the -f ( f for full )
option, which provides more information as shown in the following
example:

Process ID

// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT 17


List Running Processes

• Here is the description of all the Fields Description

fields displayed by ps -f UID User ID that this process belongs to


(the person running it)
command. PID Process ID
PPID Parent process ID (the ID of the
process that started it)
C CPU utilization of process
STIME Process start time
TTY Terminal type associated with the
process
TIME CPU time taken by the process
CMD The command that started this process

// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT 18


List Running Processes

• Here are other options/flags Flags Description

that can be used with ps -a Shows information about all users


-x Shows information about processes
command. without terminals
-u Shows additional information like -f
option
-e Displays extended information

// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT 19


Process IDs

• The operating system tracks processes through a five-digit ID


number known as the pid or the process ID. Each process in the
system has a unique pid.
• Process IDs eventually repeat because all the possible numbers are
used up and the next pid rolls or starts over.
• At any point of time, no two processes with the same pid exist in the
system because it is the pid that Unix/Linux uses to track each
process.

// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT 20


Stopping Processes

• Ending a process can be done in


several different ways.
• Using a CTRL + C keystroke (the
default interrupt character) will
exit the command. This works
when the process is running in
the foreground mode.

// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT 21


Stopping Processes

• If a process is running in the


background, you should get its
Job ID (Process ID) using the ps
command.
• After that, you can use the
kill command to kill the
process.

// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT 22


Stopping Processes

• An example here shows that a


background process is created
and its Job ID can be found with
the ps –f (or ps) command.
• After that a kill -9
command is issued to stop the
process.

// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT 23


Parent and Child Processes

• Each Unix/Linux process has two ID numbers assigned to it: The


Process ID (pid) and the Parent Process ID (ppid).
• Each user process in the system has a parent process.
• Most of the commands that you run have the shell as their parent.
• Check the ps -f example where this command listed both the
process ID and the parent process ID.

// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT 24


Zombie and Orphan Processes

• Normally, when a child process is killed, the parent process is


updated via a SIGCHLD signal. Then the parent can do some other
task or restart a new child as needed.
• However, sometimes the parent process is killed before its child is
killed. In this case, the "parent of all processes," the init process,
becomes the new PPID (Parent Process ID). In some cases, these
processes are called orphan processes.

// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT 25


Zombie and Orphan Processes

• When a process is killed, a ps listing may still show the process with
a Z state. This is a zombie or defunct process. The process is dead
and not being used.
• These processes are different from the orphan processes. They have
completed execution but still find an entry in the process table.

// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT 26


Daemon Processes

• Daemons are system-related background processes that often run


with the permissions of root and services requests from other
processes.
• A daemon has no controlling terminal. It cannot open /dev/tty (the
terminal). If you do a "ps -ef" and look at the tty field, all
daemons will have a ? for the tty.

// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT 27


Daemon Processes

• To be precise, a daemon is a process that runs in the background,


usually waiting for something to happen that it is capable of working
with.
• For example, a printer daemon waiting for print commands, or a
MySQL daemon waiting for SQL requests.

// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT 28


The top Command

• The top command is a very useful tool for quickly showing


processes sorted by various criteria.
• It is an interactive diagnostic tool that updates frequently and shows
information about physical and virtual memory, CPU usage, load
averages, and your busy processes.

// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT 29


The top Command

• By running top command, you will see the information below in the
terminal. You can end top by pressing the ‘Q’ key.

// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT 30


THE VI EDITOR
The vi Editor

• The vi Editor is a default built-in editor in the Unix/Linux system.


• vi is generally considered the de facto standard in Unix editors
because:
• It's usually available on all the flavours of Unix system.
• Its implementations are very similar across the board.
• It requires very few resources.
• It is more user-friendly than other editors such as the ed or the
ex.

// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT 32


The vi Editor

• You can use the vi editor to edit an existing file or to create a new file
from scratch.
• You can also use this editor to just read a text file.

// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT 33


Starting the vi Editor

• The following table lists out the basic commands to use the vi editor:

Command Description
vi <filename> Creates a new file if it already does not exist,
otherwise opens an existing file.
vi -R <filename> Opens an existing file in the read-only mode.
view <filename> Opens an existing file in the read-only mode.

// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT 34


Starting the vi Editor

• To create a new file named


testfile, issue the following
command:
vi testfile
• The editor will be opened in the
terminal as shown here.
• You will notice a tilde (~) on
each line following the cursor.

// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT 35


Starting the vi Editor

• A tilde represents an unused


line.
• If a line does not begin with a
tilde and appears to be blank,
there is a space, tab, newline, or
some other non-viewable
character present.

// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT 36


Operation Modes

• When working with vi editor, there are two modes to work on:
• Command Mode − This mode enables you to perform
administrative tasks such as saving the files, executing the
commands, moving the cursor, cutting (yanking) and pasting the
lines or words, as well as finding and replacing. In this mode,
whatever you type is interpreted as a command.
• Insert Mode − This mode enables you to insert text into the file.
Everything that's typed in this mode is interpreted as input and
placed in the file.

// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT 37


Operation Modes

• vi always starts in the command mode.


• To enter text, you must be in the insert mode by typing i.
• To come out of the insert mode, press the Esc key, which will take
you back to the command mode.
• If you are not sure which mode you are in, press the Esc key twice;
this will take you to the command mode.
• Try it yourself! Start by typing some characters and then come to the
command mode to understand the difference.

// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT 38


Saving and Exiting vi

• The command to quit out of vi is :q.


• Once in the command mode, type colon, and 'q', followed by return.
• If your file has been modified in any way, the editor will warn you of
this, and not let you quit.
• To ignore this message, the command to quit out of vi without saving
is :q!. This lets you exit vi without saving any of the changes.
• The command to save the contents of the editor is :w.
• You can combine the above command with the quit command, or
use :wq and return.
// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT 39
Saving and Exiting vi

• The command to save the contents of the editor is :w.


• You can combine the above command with the quit command, or
use :wq and return.
• If you want to specify/state any particular name for the file, you can
do so by specifying it after the :w.
• For example, if you wanted to save the file you were working on as
another filename called filename2, you would type :w filename2 and
return.

// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT 40


Moving within a File

• To move around within a file without affecting your text, you must
be in the command mode (press Esc twice).
• The following table lists out a few commands you can use to move
around one character at a time:
Command Description
k Moves the cursor up one line
j Moves the cursor down one line
h Moves the cursor to the left one character position
l Moves the cursor to the right one character position
Case-sensitive
commands

// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT 41


Editing Files

• To edit a file, you need to be in the insert mode. There are many
ways to enter the insert mode from the command mode.
Command Description
i Inserts text before the current cursor location
l Inserts text at the beginning of the current line
a Inserts text after the current cursor location
A Inserts text at the end of the current line
o Creates a new line for text entry below the cursor
location
O Creates a new line for text entry above the cursor
location

// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT 42


Deleting Characters

• Below is a list of commands used for deleting characters and lines in


an open file.
Command Description
x Deletes the character under the cursor location
X Deletes the character before the cursor location
dw Deletes from the current cursor location to the next word
d^ Deletes from the current cursor position to the beginning of
the line
d$ Deletes from the current cursor position to the end of the line
D Deletes from the cursor position to the end of the current line
dd Deletes the line the cursor is on
// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT 43
Change Commands

• You also have the capability to change characters, words, or lines in


vi without deleting them. Here are the relevant commands.
Command Description
cc Removes the contents of the line, leaving you in insert mode.
cw Changes the word the cursor is on from the cursor to the lowercase w end of the word.
r Replaces the character under the cursor. vi returns to the command mode after the
replacement is entered.
R Overwrites multiple characters beginning with the character currently under the cursor.
You must use Esc to stop the overwriting.
s Replaces the current character with the character you type. Afterward, you are left in the
insert mode.
S Deletes the line the cursor is on and replaces it with the new text. After the new text is
entered, vi remains in the insert mode.
// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT 44
Copy and Paste Commands

• You can copy lines or words from one place and then you can paste
them at another place using the following commands.

Command Description
yy Copies the current line.
yw Copies the current word from the character the
lowercase w cursor is on, until the end of the word.
p Puts the copied text after the cursor.
P Puts the yanked text before the cursor.

// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT 45


Word and Character Searching

• The vi editor has two kinds of searches: string and character.


• For a string search, the / and ? commands are used.
• When you start these commands, the command just typed will be
shown on the last line of the screen, where you type the particular
string to look for.
• These two commands differ only in the direction where the search
takes place:
• The / command searches forwards (downwards) in the file.
• The ? command searches backwards (upwards) in the file.
// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT 46
PIPES AND FILTERS
Introduction

• You can connect two commands together so that the output from
one program becomes the input of the next program. Two or more
commands connected in this way form a pipe.
• To make a pipe, put a vertical bar (|) on the command line between
two commands.
• When a program takes its input from another program, it performs
some operation on that input, and writes the result to the standard
output (terminal screen). It is referred to as a filter.

// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT


The grep Command

• The grep command searches a file or files for lines that have a
certain pattern. The syntax is:
grep <pattern> <file(s)>
• The name "grep" comes from the ed (a Unix line editor) command
g/re/p which means “globally search for a regular expression and
print all lines containing it”.
• A regular expression is either some plain text (a word, for example)
and/or special characters used for pattern matching.

// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT


The grep Command

• grep can be used to look for a


pattern consisting of a single
word.
• It can be used in a pipe so that
only those lines of the input files
containing a given string are
sent to the standard output.

// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT 50


The grep Command

• If you don't give grep a


filename to read, it reads its
standard input; that's the way
all filter programs work.
• An example here displays the
list of files that are created in
May using the following
command:
ls –l | grep “May”

// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT 51


The grep Command

• Here are other options/flags Flags Description

that can be used with grep -v Prints all lines that do not match pattern.
-n Prints the matched line and its line
command. number.
-l Prints only the names of files with
matching lines (letter "l")
-c Prints only the count of matching lines.
-i Matches either upper or lowercase.

// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT 52


The sort Command

• The sort command arranges lines of text alphabetically or


numerically. It arranges lines of text alphabetically by default.
• There are many options that control the sorting:

Flags/Parameters Description
-n Sorts numerically (example: 10 will sort after 2), ignores blanks
and tabs.
-r Reverses the order of sort.
-f Sorts upper and lowercase together.
+x Ignores first x fields when sorting.

// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT 53


The sort Command

• More than two commands may be linked up into a pipe.


• Taking a previous pipe example using grep, we can further sort the
files modified in May by the order of size.
• The following pipe consists of the commands ls, grep, and sort:
ls –l | grep “May” | sort +4n

// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT 54


The sort Command

ls –l | grep “May” | sort +4n

• The sort option +4n skips four fields (fields are separated by blanks)
then sorts the lines in numeric order.

// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT 55


I/O REDIRECTIONS
Introduction

• Most Unix system commands take input from your terminal and
send the resulting output back to your terminal.
• A command normally reads its input from the standard input, which
happens to be your terminal by default.
• Similarly, a command normally writes its output to standard output,
which is again your terminal by default.

// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT


Output Redirection

• The output from a command normally intended for standard output


can be easily diverted to a file instead. This capability is known as
output redirection.
• If the notation > file is appended to any command that normally
writes its output to standard output, the output of that command
will be written to file instead of the terminal.

// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT


Output Redirection

• For example, when the


following command is issued,
the output will be written to
the testls file instead of
showing on the terminal.
ls –l > testls
• You can view the file using the
cat command:
cat testls

// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT


Output Redirection

• If a command has its output


redirected to a file and the file
already contains some data, that
data will be lost.
• You can use >> operator to
append the output in an existing
file as follows:
echo “extra line” >>
testls

// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT


Input Redirection

• Just as the output of a command can be redirected to a file, so can


the input of a command be redirected from a file.
• As the greater-than character > is used for output redirection, the
less-than character < is used to redirect the input of a command.
• The commands that normally take their input from the standard
input can have their input redirected from a file in this manner.

// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT


Input Redirection

• For example, to count the number of lines in the file users generated above, you
can execute the command as shown here.

• You can count the number of lines in the file by redirecting the standard input of
the wc command from the file testls.

// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT


Input Redirection

• Note that there is a difference in the output produced by the two


forms of the wc command.
• In the first case, the name of the file testls is listed with the line
count; in the second case, it is not.
• In the first case, wc knows that it is reading its input from the file
testls.
• In the second case, it only knows that it is reading its input from
standard input so it does not display file name.

// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT


Discarding the Output

• Sometimes you will need to execute a command, but you don't want
the output displayed on the screen.
• In such cases, you can discard the output by redirecting it to the file
/dev/null. For example:
ls –l > /dev/null
• The file /dev/null is a special file that automatically discards all its
input.

// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT


STDIN, STDOUT, STDERR

• In Linux, almost all the streams are treated as if they were files.
• Just like you can read/write a file, you can read/write data from
these streams.
• You can access these streams using unique values that are assigned
to each one of them.

// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT


STDIN, STDOUT, STDERR

• The three special streams and their unique value are listed here:

Stream Unique Description


Value
STDIN 0 Stands for Standard Input. It takes text as input.
STDOUT 1 Stands for Standard Output. The text output of
a command is stored in the STDOUT stream.
STDERR 2 Stands for Standard Error. Whenever a
command faces an error, the error message is
stored in this stream.

// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT


Redirect STDERR in BASH

• If you run a command and there are error messages, you can save all error
messages into a file.
• For example, the following find command look for all files with .conf
extension under the /root directory. Any standard error from this execution will
be saved in the file find_error.txt.
find /root -name "*.conf" 2>find_error.txt
• The “2” in “2>” is the STDERR.

// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT


Redirect STDOUT and STDERR in BASH

• As an example, you can redirect STDOUT to a file named results.txt and STDERR
to file named find_errors.txt:

find / -name "*.conf" >results.txt 2>find_error.txt

• You can also send both STDOUT and STDERR to a file named output.txt using
“&>”:

find / -name "*.conf" &> output.txt

// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT


CRONTAB
What is Crontab?

• The crontab is a list of commands that you want to run on a regular


schedule, and also the name of the command used to manage that
list.
• Crontab stands for “cron table, ” because it uses the job scheduler
cron to execute tasks; cron itself is named after “chronos, ” the
Greek word for time.
• cron is the system process which will automatically perform tasks for
you according to a set schedule.
• The schedule is called the crontab, which is also the name of the
program used to edit that schedule.

// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT


What is Crontab File?

• Crontab (cron table) is a text file that specifies the schedule of cron
jobs.
• There are two types of crontab files:
• system-wide crontab files and
• individual user crontab files.
• Users' crontab files are named according to the user’s name, and
their location varies by operating systems.
• In Red Hat based distributions such as CentOS and Fedora, crontab
files are stored in the /var/spool/cron directory, while on Debian and
Ubuntu files are stored in the /var/spool/cron/crontabs directory.
// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT
What is Crontab File?

• Although you can edit the user crontab files manually, it is recommended to use the crontab
command.
• The /etc/crontab file and the scripts inside the /etc/cron.d directory are system-wide crontab
files that can be edited only by the system administrators.
• The example below shows the content of a crontab file in Ubuntu. Notice that the crontab
filename is the username of the user, fjor.

// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT


Crontab Syntax and Operators

• Each line in the user crontab file contains six fields separated by a
space followed by the command to be run.

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

// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT


Crontab Syntax and Operators

• The first five fields may contain one or more values, separated by a comma or a range of values
separated by a hyphen.
• * - The asterisk operator means any value or always. If you have the asterisk symbol in the
Hour field, it means the task will be performed each hour.
• , - The comma operator allows you to specify a list of values for repetition. For example, if
you have 1,3,5 in the Hour field, the task will run at 1 am, 3 am and 5 am.
• - - The hyphen operator allows you to specify a range of values. If you have 1-5 in the Day
of week field, the task will run every weekday (From Monday to Friday).
• / - The slash operator allows you to specify values that will be repeated over a certain
interval between them. For example, if you have */4 in the Hour field, it means the action
will be performed every four hours. It is same as specifying 0,4,8,12,16,20. Instead of
asterisk before the slash operator, you can also use a range of values, 1-30/10 means the
same as 1,11,21.
// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT
System-wide Crontab Files

• The syntax of system-wide crontab files is slightly different than user


crontabs. It contains an additional mandatory user field that specifies
which user will run the cron job.
* * * * * <username> command(s)

// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT


Predefined Macros

• There are several special Cron schedule macros used to specify common intervals. You can use
these shortcuts in place of the five-column date specification.

Macros Equivalent To Description


@reboot None Run once at start-up
@weekly 00**0 Run once a week
@daily 00*** Run once a day
@midnight 00*** (same as @daily)
@hourly 0**** Run once an hour

• For example, use the following to restart “my_script” after each reboot:
@reboot /var/tmp/my_script

// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT


Linux Crontab Command

• The crontab command allows you to install, view , or open a crontab


file for editing:
Commands Description

crontab -e Edit crontab file, or create one if it doesn’t already exist.

crontab -l Display crontab file contents.

crontab -r Remove your current crontab file.

crontab -i Remove your current crontab file with a prompt before removal.

crontab -u <username> Edit other user crontab file. This option requires system administrator
privileges.

// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT


Crontab Restrictions

• The /etc/cron.deny and /etc/cron.allow files allows you to control which


users have access to the crontab command.
• The files consist of a list of usernames, one user name per line.
• By default, only the /etc/cron.deny file exists and is empty, which means
that all users can use the crontab command. If you want to deny access to
the crontab commands to a specific user, add the username to this file.
• If the /etc/cron.allow file exists only the users who are listed in this file
can use the crontab command.
• If neither of the files exists, only the users with administrative privileges
can use the crontab command.
// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT
Cron Jobs Examples

• Below are some cron job examples that show how to schedule a task
to run on different time periods.
• Run a command at 15:00 on every day from Monday through Friday:

0 15 * * 1-5 command

• Run a script every 5 minutes and redirected the standard output to


dev null, only the standard error will be sent to the specified e-mail
address:
MAILTO=email@example.com
*/5 * * * * /path/to/script.sh > /dev/null

// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT


Cron Jobs Examples

• Run two commands every Monday at 3 PM (use the operator &&


between the commands):

0 15 * * Mon command1 && command2

• Run a script every day, every hour, on the hour, from 8 AM through 4
PM:
00 08-16 * * * /path/to/script.sh

// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT


Cron Jobs Examples

• Run a script on the first Monday of each month, at 7 a.m.

0 7 1-7 * 1 /path/to/script.sh

• Run the a script at 9:15pm, on the 1st and 15th of every month:
15 9 1,15 * * /path/to/script.sh

// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT


E-learning References and Credits

• TutorialsPoint
• Scheduling Cron Jobs with Crontab

// AAI • Cloud Technologies (CAI2C04) TEMASEK POLYTECHNIC I School of Informatics & IT 82


CTEC
Next week…

You might also like