0% found this document useful (0 votes)
17 views23 pages

Linux CH 5

Linux is a widely used open source operating system that powers many of the world's supercomputers, servers, desktops, and embedded devices. It was created by Linus Torvalds in 1991 and can be freely modified and distributed. This chapter provides an overview of Linux, describing its history, key features like multi-user support and security, and popular distributions. It also outlines the steps for installing Linux, including choosing a distribution, running the installation program, and removing or upgrading software packages later on.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views23 pages

Linux CH 5

Linux is a widely used open source operating system that powers many of the world's supercomputers, servers, desktops, and embedded devices. It was created by Linus Torvalds in 1991 and can be freely modified and distributed. This chapter provides an overview of Linux, describing its history, key features like multi-user support and security, and popular distributions. It also outlines the steps for installing Linux, including choosing a distribution, running the installation program, and removing or upgrading software packages later on.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Linux Basics

5.1
NTRODUCTION
123
ncider two facts: First,
more than 90%
System. S Second, the most
Widely used search
of today' s 500
fastest
Doesn't this sound
interesting? engine, Google, uses supercomputers use Lnus
Linux
Low cost and
as its
Operating System to
superlor reliability have
tablets,
c
and personal
computers to gained space for
Linux in a wide
mainframes and variety of devices, Iron
[n the previous chapters, the supercomputers.
rticular operating system has beenoperating system is described in general. Except for some
particu
considered during the
description of various concepts of theexampics
y
This chapter is dedicated to a operating y em.

ogramming, related to the specific operating system: Linux.


progra Linux
Operating System Practical concepts,
overview of the Linux are described in this chapter. The incudg
Operating System. This follows chapter starts witn an
installation. The
remaining sections are
a
description of the step by step description ot LInux
and its concepts. Various shell commands
important for laboratory work. They include a description of the
shel
categorized as directory related, file-related, general purpose, filters,
Drocess-related and other are introduced next. This follows a
introduction to different editors and some description of shell programs (shell scripts), an
examples of shell programs.

5.2 LINUX OVERVIEW

Linux was first developed by Linus Torvalds, a student in Finland, in 1991. But now, Linux is not
owned by anyone. No one company or individual "owns" Linux, Iike Windows is owned by a single company
Microsoft.
Linux is the most famous free and open source Operating System. Open source Operating Systems are
available in source-code format rather than as compiled binary code, Free software means not from a money
point of view. But, software that is free. like Linux, is distributed along with its source code. So, anyone who
receives it is free to make changes and redistributeit. You can change the source code of Linux as per your
equirements. Not only this, but you can also distribute this modified OS. You need to be concerned that you

code with this OS.


ave to provide your modified source

and as a result, many Tlavors of Linux are available in the market.


Many people have done such work, Fedora and CentOS, Debian and
Linux and its derivatives, Such as
Dome known ones are Red Hat Enterprise
Linspire, and PCLinux.
Ubuntu and Linux
Mint,
Uerivatives, such as reatures of UNIX, It is a multi-user, multi-
famous. It uses most oI the
Day by day, Linux is becoming User Intertace (GU). It is quite robust and secure.
a handy Graphical
taskin
Ag Operating System that supports with Windows).
Linux systems (as
virus attacks on
WIlrarely hear about computers, mobiles,
tablets and embedded svste

devices from personal


LInux can be found on many
to nainframe mputers and supercomputers.
nc wotId
O
Linux today, you can Google it
is happening
know what UNIX clone It
"you are interested to a
not O. Linux is not a t was
1s
in chapter 1,
Linux
RC to
S O note that, as explained
of software that
and a collection of that together creates
Linux
Linux kernel and
kernel
is the
distribution is
written m scratch. A Linux in general use,
as in generalac
LInUx wll be
Linux will
considered.
be considered an operating system

an operating now
onwards,
g System. But from
Linux Operating fiystem
124

5.3 INSTALLATION AND UPGRADE


section. The
section begins wI dcheription of the
A description of Linux installation is given in this the Installation steps
install. Aler this,
ypes ot Linux installations. This follows a descrintion of
which Linux to
removal of the 5oltware program
installation and
are described. After completion of a description of the installation,

are given.
1o VISit a
readers are rcquested website
To get about LinuN installation and upgrade,
detailed information
So, rClders are requested
installation procedures.
Such as www.linux.org. Different flavors of Linux have different
to go through detailed user manuals of particular Linux distributions.

5.3.1 Types of Linux Installation


There are four different types of Linux installations Dual Boot, Live CD/DVD Booting, Virtual Installation
and Fresh Installation. These types are described below:
1. Dual Boot
Computer systems can have more than one Operating System.
Linux can be installed along with other Operating Systems, such as Windows.

In such situation, a user has to decide which Operation System to boot into during the boot
process, i.e., when the computer system starts.

2. Live CD/DVD Booting


Linux can be run as a completely bootable Operating System from CD/ DVD. For this purpose,
many Linux distributions provide such bootable CD/DVD, referred to as Live CD/DVD.
When a computer system is booted from CD/DVD, required files are loaded into the main memory
from CD/DVD. Operating System runs using these files.
When a computer is rebooted after removing CD/DVD, it will boot from the old Operating
System
installed in the computer system.
This provides an easy way to try out various Linux installations without actually installing them.

3. Virtual Installation
Linux can also be run as a virtual machine inside
another Operating System. For this, a
has to install some virtual server application such
usc
as
VMWare and then install Linux under
host software. u
Here. Linux runs above the host
Operating System, providing all
Linux functionalities.
4 Fresh Installation
This is the most popular installation. It installs Linux as the
Here, the hard disk is formatted, nd if there is
only Operating System
em of the computer
it is removed.
any existing Operating System in the compulet
The following sub-sections describe this kind of
installation
Linux Basics

5.3.2 Installations Steps


125
pebian GNU/LInux is a
y obtained aral well-established, non-profit,
be easily
IIcan installed. It forms the base non-commercial, free, open-source
and Xandros. for many
use Operaling >ystCm
ser-friendly distributions like Ubuntu,
Linspire
As it is not possible to
provide installation
the Debian distribution are
given here. Similar instructions for all Linux distributions, general steps to
distributions. steps can be followed Insta
with minor variations to install otner
1 Get the Linux
distribution
Most of all
Linux
the distributions
are available
required CD/DVD can be obtained
as a software
package stored on CD or DVD, S0,
downloaded from the from the related vendor. Or, Linux
through the internet and can be burnt on distribution
related website can De
option (widely used CD/DVD. Another
nowadays) is to create a bootable pen drive with
Whatever the source this distribution.
may be, it is a must to have
2. Configure PC to boot from a Linux distribution to install it.
CD/DVD or pen
Usually, the
drive:
computer boots from the hard disk and uses
disk. Configure the
computer to boot from CD/DVD or pen drive Operating System installed on a hard
To get BIOS by changing the BIOS boot order.
setup tools, press the 'Del' key while
"boot sequence" from BIOS booting the computer. Find the option of
setup tools. By pressing the page up/page down
or USB drive as the
first bootable device.
keys, set the CD/DVD
After this, press the Esc'
key and choose the option SAVE AND EXIT SETUP.
3. Start an actual installation:
Insert a bootable CD/DVD pen drive with Linux distribution and restart the
or
computer.
After restarting, the computer will boot the Linux kernel located on the
CD/DVD or pen drive.
This starts the actual installation of the Linux Operating System.
4 Partition hard disk
The whole hard disk can be dedicated to the Linux Operating System without
partitioning it.
But, this will create a problem in retrieving data if something goes wrong with the Operating Svstem
in the future.
So, it is better to have multiple small partitions on a hard disk than one big partition. Data stored

on different partitions will not get affected it some problems arise With Operating System.

two partitions to install Linux:


Each Linux distribution requires mainly
(Boot) Partition: files of the oneras
of the hard disk. All the required
This should be a primary partition em

are loaded in this partition.


the Operating System and other ene.
depends upon the
size of re
The size of the boot partition
to. be installed.
applications that need as eXt3 (Or the latest
partition one. evtdi
to format this
Specify the file system (or partition type)

Swap partition: in and out


processes during swapping vhen
whe
area for moving
used as a swap
This partition is
full.
the main memory is
Linux Operating System
126
least be twice the
amount of physical me
g e n e r a l , the size partition should at
of the swap size of the swap
emory
has 4GB RAM, the ition
partis.
O the computer system. For example, if the computer
should be at least 8GB.
Specity file system (or partition type) to format this partition as swap

other logical (or extended) partitions to


Along with these two partitions, the computer should have
store user data. But, such partitions are not mandatory.
All Linux distributions provide some tools to partition the hard disk. One tool of such kind is FIps

First non-destructive Interactive Partition Splitter).


5. Install Linux kernel
After providing proper partitions, the installation process will proceed. When asked, select extra modules
to add to the Linux kernel as per requirements. Provide hostname, domain name and ISP's server IP address
as per requirements.
After this, choose 'CD-ROM/DVD' for the installation procedure. Also, choose the setting 'make system
bootable'. Install 'GRUB' in the master boot record.
Create a rescue disk when asked to do. A rescue disk is useful when a system becomes unbootable
due to some problem.
In the end, reboot the system and Linux is installed. Remove the CD/DVD or pen drive and undo
the changes made in the boot sequence.
6. Complete the installation process
Insert CD/DVD pen drive again in the drive. It will be scanned for available
or
packages to install.
After installing these packages, other packages can be downloaded and installed
if an internet connection
is available.
7. Configure the basic Linux system:
After rebooting
the new Linux system, it is time to
provide some basic configurations. When asked
if you want to md5 passwords and if you want a shadow
use

internet for technical details)


password system, answer 'yes". (Surf the
Provide the password for the 'root account. The root is an
administrator account.
Create other user accounts as
per requirement by providing a username and
Remove PCMCIA when asked to remove it. password.
Configure your system to use your ISP if you need it.
Now, system is ready to use. Note that
your different Linux
procedures. So, explore their installation material, distributions may follow different
either from a book or the
installation
Operating System. (AIl the Best..!) internet, before installing any Linux

5.3.3 Upgrade the System


The system can be upgraded by installing new sorware applications as
applications can also be removed if per requirements, Similarly, existing
they are not required.
In Linux, software
need
application comes In tne
O pacKages. So,Tom
to
toinstall or remove related software install or remove a
pac kage,
appiicaOns. IKeured you
or found from another
source, such as a CD/DVD or pen drive.packages can be
downloaded from the interne
Debian and its variant Linux
remove
Operating Systems such as
Ubuntu, provide
packages. Both of these commands are described below: two commands and
to insta
Linux Basics

em
apt-get install:
ory
ion Syntax : 127

Usage : apt-get install


Installs packageList
. apt-get remove package or
packages specified
to
Syntax packageList.
apt-get
PS
Usage: Removes
remove
packageList
package or
packages specified
packageList.
5.4 SHELL

es
SS This section describes various
cribes what the shell 1s. The next
descrit
concepts related to a shell. It starts
of the shell. Next are Wild
topic covers the working of the with the basics about the snell, w
n characters, a set of special shelI, known as the interpretive
redirection, filtering and pipes provide a characters used for cycl
pattern-matching. The next three topies
Redirection provides a way to re-direct the wayandto combine simple commands to perform complex tasks.
e
that use both standard input as well as
input output of processes to various files. Filters are commands
standard output to
the output of one process to another perform their tasks. Pipes provide a way to feed
next. The last topic covers shell
directly. Shell special characters, called
metacharacters, are summarized
variables.
5,4.1 Basics

Suppose Someone asks the


question, "What is Shell ?
The answer to this question can be different from different viewpoints. Shell is an interface.
Shell is a
command interpreter. Shell is a
programming language. Shell is a process. Different viewpoints are described
below:

Shell- As an interface
Shell is an interface between the user and the kermel.
Users directly interact with the shell. Shell provides a prompt (command prompt) to the user where
the user can enter their commands.
executes these commands.
Shell interacts with the kernel and

Dnel- As a command interpreter:


Shell is a command interpreter.
user on a prompt. it thoroughily examines it for special cters
It reads a command entered by a
command.
it rebuilds the simplified
Such as <'. If it finds any,
from the command.
white spaces
unnecessary
also removes
kernel can understand it easily a.

in such a form so that on,


command
translates a
hus, it
command to
the kernel for execution.
presents the simplified

Shell As a programming language also.


language functionalities like ooping
onell is a programming programming.
It provides and
features
for
ssary
lt provides all the
variables.
supports shell scripts. Snell scripts also include nu:
Dranching. It also programs
velon programs
k n o w n as
known
develop
used to
These features
fea are

Commands in their syntax.


Linux Operating System
128
Shell- As a process
At last, the shell is a process.
when the user logs in. This process, and
Kernel executes the shell program to start the shell process
It terminates when the User logs out of the
so shell, remains in execution until the user logs out.
system.
to work n.
During its execution, it creates an environment for users
It requires kernel services to
This process executes in user has limited functionality.
mode and so
a disk. To request
such as reading a file from
pertorm specific tasks, particularly related to devices,
services from the kernel, system calls are used.

available in Linux. These are the Bourne shell, C shell and Korn
There are mainly three different shells
shell.
which makes it difficult
The Bourne shell very compact syntax,
(sh) is the oldest among all shells. It has a

C Shell (csh) contains syntactical structures


for new users. However, it is very efficient when used by experts. The
command aliasing and command history. The
similar to the C language. It provides specific functionalities like
is an extended version of the Bourne
Korn shell (ksh) is the superset of the Bourne shell. The Korn shell
shell that includes many of the features of the C shell. It is very powerful.

5.4.2 Interpretive Cycle


The working of a shell can be deseribed as an interpretive cycle. Here. the shell operates in a simple
loop: it reads a command, interprets it, executes it and then waits for another command by providing a 'prompt
The following Figure 5.1 gives an idea about this cycle.

Read
Comnand

Display Interpret
prompt comand

Executee
conand

Fiqure 5.1: Interpretive cycle of a shell


Linux Sasics

129
The shell performs the
tollowing activities in its
The shell displays the
interpretive cycle:
prompt. Then,
a user to enter a it waits for
command.
When a command 1S
entered, the shell
2 reads the command. It scans the
Tf it finds any such character, it command line for meta characters.
recreates the command in
It then passes the command to the
simplified form.
kernel for execution. During the execution of a
simply waits. It normaly does not do command, the she
any work during this time.
After the command execution is
complete, the prompt reappears. Shell is ready to start a new cycle
Users can enter another command now. now
This cycle starts when a user
logs in to the system and
terminates when the user logs out of the system.

543 Pattern Matching The Wild Cards


Shell proVIdes a set of
special characters to match patterns. These characters are known as Wild cards.
They can be used to match
any patterns, including filenames.
For example, is one such of
type character, and it is used to match any number
a command Is of characters. So, providing
prog lists out all the files starting with the name prog.
The following table given in Figure 5.2 summarizes wild cards with their matches.
Wild-Card Matches
A single character

Any number of characters, including none

[abc] A single character - either a, b orc

x-z] A single character within the range x to z

a-ce-gl A single character within the range a to C, e to g

A single character that is not a, b or c


[labc]
A single character that is not within the range x to z
[x-z]
Strings starting with must be explicitly matched
cards
Figure 5.2: Wild

Files
.4.4 Redirection: The Three Standard
from the sinell opens Dtndard input, 2. Standard Outnut
Every program that a user executes means
means of
of communication pro
c o m m u n i c a t i o n between the programs and exist

and 3. Standard Error. These files provide the primary


Tor as long as the process runs.

described below:
These three standard files
are

The standard input file: from standard input.


data for a process
a way to
read input
lt provides
keyboard.
default, the
standard input is the
By

Linux Oper. Sys./ 2022/ 17


Linux Operating System
130

The standard output file :


it provides a way to write output data for a process

By default, the standard output goes to the monitor.

The standard error file:


execuron to the standard Ontos
provides a way to report errors encountered during process output.
By default, the standard error goes to the monitor.

keyboard and writes output data & error mesSaoa


ges
Snort, by default, any process reads input from the
to the monitor (or other display devices). But, this default behavior of a prOcess can be changed.

ne process can be told to read input from another source, such as a file or other process, instead of
a keyboard. Similarly, the process can be told to write output to another destination, such as a file or other

process, instead of a monitor.


This technique of changing default standard input, standard output or standard error is called "Redirection'
The redirection of three standard files is described below:

1. Re-directing Input
Here, a process is told to read input from some file stored on a disk instead of a keyboard.

For this purpose symbol is used with a file name.


General syntax: command < filename
Example:
WC<test.txt

wc command will read input from a file named test.txt rather than a keyboard.
2. Re-directing Output:
Here, a process is told to write output to some file
kept on disk instead of a monitor.
For this purpose >symbol is used with a file name.
General syntax: command > filename
Example:
WC test.txt
output.txt
we command will write output to a file named
output will not be output.txt rather than monitor. S0, the
displayed on the monitor screen but
a
will be stored in
3.
Re-directing Error a file dre
Here, a
process is told to write errOr
messages encountered
on disk instead of a monitor. during its execution to some file
For this purpose
2> symbol is used with a file name.
General syntax: Command 2>
filenamee
Example:
Wc test.txt
2> error.txt
(Here, 2 is file
descriptor number.)
Linux Basics

we command will write


error 131
error messages wil not be messages to aa file named
Sges error.txt rather than
displayed on a
monitor
thanaa monitor.
screen but will be stored in a
Thererore
Here, symbols used'< and ih
ed at the prompt
n t e r e d
and scans it for pcclal characters called metacharacters.
such types of The shell reads the command
When it encounterS tne
Symbol,
it
special characters.
opens the specified file for a read operation.
ncounters the
symbol, 1t opens the In a when
ell creates it before
the shell
specified file for a write Simaw
operation. Here, if a file does not
executing the
command. And, if the file exists, it will be overwritten. exi
addition to
In and, another symbol
fnctead of overwriting file contents, it used for redirection is > . It works the same as thesymbo
appends the output to the file.

5.4.5 Filters

Different Linux commands contain


different characteristics regarding the use of standard inputs and outputs.
Some of them use standard input only. Some of them use standard output
only. Some of them use neither standard
nput nor standard output. Some of t.em use both standard input as well as standard output.
Based on this, Linux commands be classified into four categories:
can

1. Basic file-handling commands like cp, mv and rm, and directory-oriented commands like mkdir, rmdir
and cd use neither standard input nor standard output.
2. Commands like ls, who, and pwd don't take any standard input, but they send their output to the
standard output.
3. Ip uses standard input but produces no standard output.
4. Commands like cat, we, od, emp, and gzip use both standard input and standard output.

called Filters. Their dual capabilities of handling standard input as


Commands in the fourth category are

wCl as output make them very powerful text manipulators.

Example
Consider the.following command:
command is a text-based calculator.)
result.txt (bc
be< input.txt >
and produces output to the screen of a monitor
firom a keyboard
takes input
By default, the bc command both are
re-directed.

standard input, as
well as output
C T e , its perTorms required operations, and stores
ores
from a file named
pu.t ,
this example, bc reads its input display
in nor monitor is used to output.
used to take input
result.txt. Neither
keyboard is
put tothe file
called filters.
Such commands are

5.4.6 Pipes can be fed to the


The
standard output of one process
processes.
two
connect
called "Piping'.
In Linux, it is
S possible
to is
perform complex tasks
mechanism

This it possible to
Standard inpu another
process.
with
each
other. This
O to
connect

Pipes allow simpll e processes

blocks.
USing simple prOcesses as building
Linux Operating System
132
Command2
Syntax: Commandl Iile. Instead, it is d.
Ouput ot Command1 is transferred to neither
monitor nor
anotner

nor from any file.


fro
directly
c

reads neither
from the keyboard Instead
fed to the input of Command2. Similarly, Command2
1.
it directly accepts the output produced by Command

Example
mechanism.
Consider the following example to understand the piping
We-1
who
1his output is directly fed to the we.
Fiere, who command produces a list of users, one userper line.
it gives the number of users who
Command. It counts the number of lines in an input. So, in this example,
have logged in currently to the system.

Difference between Redirection and Pipes


Redirection connects processes with files, while Pipes connect processes with other prOcesses.

5.4.7 Metacharacters
Metacharacters are a special set of characters. They contain special meaning to the Linux shell.

When a user enters a command, the shell reads the command and scans it to find metacharacters. If it
finds any such character, it recreates the command in the simplified form before presenting it to the kernel
for execution.
Metacharacters are nothing for commands, but they are important to the shell.
Various metacharacters have been described in previous sections. The following table given in Figure 5.3
summarizes the metacharacters used in Linux.

Suppose that the user has a file named prog, and he wants to remove
that file. So, he
like this - gives a command

rm
prog (Tm command removes the file.)
But, here, the shell interpretsas a metacharacter. It will be matched with any other characters.
any file starting with the name prog will be removed. So, what is Consequen
the solution
If a user wants to treat any of the
metacharacters as a normal
to this problem?
of shell, then there are two solutions to solve this
character, i.e., he doesn't want interrere
Both of these problem. These two solutions are
two remove the
special meaning of metacharacters. These two Escaping and Quoll
Escaping: ways are described as follow
Provide a \
(backslash) before
the wild card to
remove
So, in our
example, a command can be (escape) its special meaning.
given as:
rm progl*
Quoting
Enclose the metacharacter, or even the
entire
So, in pattern, within
our
example, a command can be given as:
quotes.
rm
progt
Nothing within these quotes 1S
special meaning. interpreted by the shell.
Shell lefts it S
alone without conside
LinuxBasics

133

am Metacharacter
Description
Linux interprets a
space as a
ctly separator, not as a character.
ead, A wild card character that matches any number of characters: For example, aDe all
the files that start with 'abc

A wild card character that matches any single character, Thus 1 s 222 lists files having names

3 characters long.
VC
A set of characters that can be matched. Thus ls [a-c]+ lists all files that begm wi
who
b, or C.

1s
whose value
Indicates that the following text is the name of a shell (environment) variable
$
to be used.

Separates commands to form a pipe.

If it Re-direct the standard input.


ernel
to replace current contents.
Re-direct the standard output
contents.
to current
Re-direct the standard output to append
5.3
current contents.
the standard error to replace
Re-direct

to current contents. ee
standard error to append
mand Re-direct the

name.
Introduces a job

ently, process
into the
background.
Place a
command. d
executed as a single
commands to be
of
rence 0 Encloses a sequence

oting. substitution.

lows: Precedes a history one line.


on
that a r e
commands
(or pipes)
of first
Separates
sequences
second of which is
executed only if the
the
or pipes,
commands
sequences
of
&& a r a t e s two
Separa is executed only if the first
which is executed o

Succeeds. second of which


the
or pipes,
commands

sequences
of
Separates two
character, as in *
fails. treated
as
a plain
it 1s
so
m e t a c h a r a c t e r ,

the
Use
Sed to "quote" Figure 5 . 3 : Metacharacters

ing its
134 Linux Operating System
5.4.8 Shell Variables
LKe In other high-level programming languages, the shell also supports variables. They are
re used to used to
store
values. Here, variables divided into
are two categories:
User defined variables, and
Linux defined variables or System variables.

These two categories are described below:

1. User defined variables:


These variables for their
are defined by the users either on prompt or in shell scripts own purposes
Rules to specify variable names
Variable names can begin with an alphabetic underscore character, followed
or
by one or more
alphabets, digits or underscores. Variable names do not contain space or commas and other characters.

Case sensitivity:
Variable names are case sensitive, 1.e., Tenp and temp refer to two different variables.

Variable assignment:
A variable
assignment is of the form:
Variable=value
(no space around =)
For example, count=5

Variable evaluation:
An evaluation of a variable requires the $ as
For example,
a
prefix to the variable name.
echo $count, or
total=$count.
2. Linux defined variables or
System variables
These variables are defined by Linux itself.
They are used to customize the working
environment.
Generally, they contain some default values.
Users But, the user
can also read the values already set in can set its
these variables.
own values in these variaobles.
L i n u xB a s i c s

stem The 1towing table describes some of the 135


Variable
system variables.
store
PSI Primary prompt string Description
(default S, #)
PS2
Secondary prompt string (default
>)
PATH Search path
for
bin:/usr/bin:) commands; multiple pathnames are separated witha cod
HOME Default argument for the
cd command; contains the pathname of the nonc di
Oses. LOGNAME Holds user's login name

MAILPATH List of filenames, separated by colons (:), to check for incoming


ma
MAIL Name of file to check for
more incoming mail
cters. MAILCHECK Specifies how often to check for mail in SMAIL or SMAILPATH. If set to 0, the
mail is checked before each
prompt. (default 600 seconds)
IFS Internal field separator (default space, tab, or new line)

SHELL Pathname of the shell

TERM Specifies your terminal type

TZ Specifies Time zone

5.4: System variables


Figure

5.5 COMMANDS

commands. For the sake oI user understanding, these commands are


1nis section describes various Linux
below:
ved into six different categories, as given
Related: pwd, cd, mkdir, rmdir
Directory
mv, chmod,
wc, diff, cmp, comm, split
ile Related: cat, Is, cp, mv,
man
who, tty,
3. echo, pass wd,
ueneral Purpose: cal, date,
4"FilterS: head, tail, sort, tr. grep
cut, paste,
kill, top
Process Related: ps, time, tee, set
hostname, exit, expr,
S. 6. Otners: su, sudo,
logname,

the options are described here. (Becaus


use
But not all
with many options. 11-knownoptions are described here.
emember that some commands
ne
some of the well-
it requires a commands...!!)
Only led description of all commands.
detailec
ate book on Linux command
for a

Users refer to online help provided by man

and examples.
options,
usage,
syntax,
mmand description
includes
Lng Sy
136

5.5.2 Directory Related: pwd, cd, mkdir, rmdir, dirname


1. pwd:
Print Working Directory

Usage: Print working directory name.

Syntax: pwd
2. cd:

Change Directory
Usage: Change working directory.
Syntar: cd Tdirectory
Examples:
cd.change working directory to home directory
cd .change working directory to parent directory
cd /usr/lib ..change working directory to absolute path /usr/lib
cd doc/letters ...change working directory to relative path doc/letters.
3. mkdir:
e
Make irectory
Usage: Creates new directory.
Syntax: mkdir directory

Examples:
mkdir Test ..creates a new
directory named Test.
4. rmdir:

Remove Directory

Usage: Removes empty directory.


an
It the
Syntax: rmdir directory
directory is not
empty, it will not be
removo
Examples:
rmdir Test ..
removes the directory
5.
named Test if it
dirname is empty.

Directory Name
Isage: Displays parent directory name or the
last
Syntax: dirname filepath component in the file
path.
Examples:
dirname
home/india/sample
ple.txt..displays home/india that is
directory
ory of sample.txt
L i n u xB a s i c s s

K5.3 F i l e Related: cat, cp, rm,


mv, In, Is, 137
cat:
chmod, wc, diff, cmp, split
Usage: Displays Tile
contents, creates a
Syntax:
new file or
appends data to an le.
o
cat
file
cat f i l e
displays file contents.
Creates new file.
cat >> file
appends data to an existing file.

2. Is
List files

Usage: List out contents of a


directory
Syntax: ls
[directory]
Options:
a list out all files, including hidden ones
2
d list only directories
F mark directories with/, executable files with*, symbolic links with @, and sockets with =

T long listing showing protections, number of links, owner, size, and time of last

modification
S size in kilobytes

3. cp

Copy command

file or group or
est 1000o o e
Usage: Copies a

file2...) target
Syntax: cp [ -irp 1 filel
Options: overwriting a destination file.)
i: Interactive copying
(Asks before
directory structure.)
r: Recursive copying
(It copies

mv
file
Move / Rename or group
of files.
a tile
moves
file or
Renames a
Usage: targer
1file2 ...]
mv I -if1 filel
Syntax:
filel, to file2
Examples ..Renames "

file2 the directory "archive


file1 "old" file to
...
Moves
archive/

mv old
Linux oper.
Sys./ 2022/ 18
Linux Operating System
138 m

5. rm.

Remove file
Removes files (Deletes files)
Usage
Syntax: n1i 1-ill-r] file
Options:
i: Interactive removal (Asks before each removal.)

r: Recursive removal (Performs recursive


deletion in a directory.)
file als0.)
f: Forceful removal (Removes write protected
6. Wc
Word count
Syntax: WC Lfile)
Usage: Counts the number of characters, words and lines in a given input file. If a file is
not given, it takes input from standard input.

Options:
Counts number of lines
W Counts number of words
Counts number of characters

7. chmod:

Syntax:
chmod [ugoa][+ =][rwx file (Relative permissions)
chmod ### file (Absolute permissions)
Usage:
Changes file permissions
In Relative mode, the first
options indicate whose access is
to be changed u (user,
g (group), o (other), or a (al). The second you
options indicate the type of action
(delete), or =
(set). The last options
specify the access to be
+ad ). ite
delete), or x (execute). set (read), W
r
(W
In Absolute mode, three numbers
Each number is represent the protections for
a sum of I (for execute the user,
user, group and others
group an
read access). access), 2 (for write/delete access) an
ror write/delete access) and 4 (TOr

Examples:
chmod 0-rWX
test.out
.denies others from to
file test.out having any a
cess

and has no Tect on user/group


access effect
chmod 750 test.out
..Sets full
access for the e x e c u t e

for the user, reaa a


group and no access for thers
O
L i n u x B a s i c s

cmp:

139
Compare
Usage:
Compares two files and
Syntax: gives the location of the first
cmp filel file2 misma
diff:
9.
Usage Compares two files, gives the
to make two files location of mismatch, as well
identical. as
suggests es

Syntax diff filel file2


10. comm:

Compare sorted files


Syntax: Comm I -123
is filel file2
Usage: Compares sorted files filel and file2
line by line. With no options, produce three
column output. Column one contains lines
unique to filel, column two contains lines
unique to file2, and column three contains lines common to both files.

Options:
1: suppress lines unique to file1.
2: suppress lines unique to file2.

3: suppress lines that appear in both files.

11. split:

Splits a file into multiple files

loptions] filename newfileprefix)


Syntax split
Default names for new files will be xaa, xab,
into multiple files.
Usage: Splits filename Suffix for new files will be aa, ab, ac etc.
etc. if newfileprefix is not given.
xac

Options: lines. Default sie if 1000.


contain n
file will
n : each new

contain n bytes.
new file will
b n: each

man
passwd, who,
tty,
5.5.4 General date, echo,
Purpose: cal,

. cal:

Calendar
Usage: Displays calendar.

current month
calendar of the
Syntax: ..displays
calendar of the particular year
cal ..displays
calendar of the
particular month and year
yeart
cal .displays
montht
yeart
cal
140
Linux Operating System
2. date:

Syntax: date
Usage: Displays current date and time
3. echo:

Syntax: echo -n) message

Usage: LDisplays message, as well as evaluates variables

Examples:
echo "Hello world...!" ..displays a message

echo ..evaluates variable count


Scount
echo -n "Hello India..!"...do not consider trailing new-line character
4. passwd:

Syntax: passwd

Usage: Changes the password of a user


5. who:

Syntax:
who ..displays all users
who am i ...displays user of the current shell only
Usage:
Displays information about all users who have
logged-in to the system currentiy,
Information includes username, device name, date and time of logging in, and machine
name from where a has
user
logged in.
6. tty:
Syntax: tty
Usage:
Displays filename associated with terminal
Remember that all devices are treated as files in Linux
7. man:

Syntar: man Toptions]


title
Usage:
Print entries from the online
reference manuals;
In short, it find manual entries
displays online help about the by keywo
call or function name. title:; the title can be a command name, sy
Examples
man Is .. will
display man-page
... will search for all (help)
man test for ls command
appears
help pages in which the
man
keywo
man
..if ever you have
forgotten how to use 'man
L i n u xB a s i c s

cem Filters: head, tail, cut, paste, sort, tr, grep 141
head:

Syntax: head I-n] file


Usage:Displays
if used
the top of
the file.
By
with the -n
default, it displavs the first 10 lines of
option, it
displays first 'n' lines of a file.
a file, Dut
Options:
n: indicates the number of lines to be
Examples: displayed from the top of a Te.

head test.txt
.displays first 10 lines of a file test. txt
head -20 test.txt
.displays first 20 lines of a file test.txt
2 tail:

Syntax: tail -n] file

Usage: Displays the end of the file.


By default, it displays
the last 10 lines of a file, but
if used with the -n
option, it displays last 'n' lines of a file.

Options:
n: indicates the number of lines to be displayed from the end of a file.

Examples:
tly. tail test.txt ... displays last 10 lines of a file test.txt
ine
tail -20 test.txt ..displays last 20 lines of a file test.txt

3. cut:

Syntax: ... to cut columns


cut -c list Lfile..)
. to cut fields
I-d char] I-s] Lfile
cut list
columns or fields from an input file.
Extracts specific
sage: Cuts a file vertically.

Options: the list.


columns as given in
C: extract specific char
in the list
or delimited by
as given
f: extract specific fields
em
characters 5-15 and 20-25,
Examples: ..Cxtracts two
columns having
test.1xt
5-15, 20-25 second and third columns
cut -c extracts
. . .

test.txt

cut f2,3

st paste: filel file2..


- d char
paste
Syntax:
Usage:
Pastes files.
Linux Operating System
142
means data are not appended
files vertically. Here, vertically
to
It combines two or more

the same lines.


the end of other files but merged on

(Try practically. Use man.)

5. Sort:

Syntax: Sort loptions] file


file. Data sorted line by line.
Usage: Sorts data in a are

Options:
c: check that input is in sorted order
case
f: sort upper and lower case letters together, i.e., 1gnore
m list: merges sorted files in the list

n: sort by numerical values

o file: send output to file


r: reverse the sorting order

t char: use delimiter char to identify fields

u: remove duplicate lines

k n: sort on the nth field

k m,n: start sort on the m field and end sort on the nth field
k m.n: start sort on the n column of the mth field
6. tr:

Translating Characters
Syntax: tr -cds] [string1] string2]
input
Usage: Translate characters in a file. It is used to
replace characters, delete characters, chang
case of a text as well as compress
multiple consecutive characters.
Options:
c: translate character not in
stringl
d: delete a character in stringl from the input
s: truncate repeated characters given in
stringl from the input.
strings: any pattern can be given as
strings
input: input can be standard input or
re-directed file,
Examples:
or piped process
1r
1 < test.txt
replace all : from the
tr a-z]' TA-Z]'
<test. Lxt test.txt file wi
.translates lower
tr -d T
<bdate. Ixt case letters to uppe case
.delete / from
tr -S
<test. txt bdate.txt file
...Compresses multiple
consecutive spac
i n u xB a s i c s

H r e p

to 143
Syntax: grep
loptions) patlern
Usage Displays that match the filenamel8)
lines from
files
programming. (EXam point of given pattern, Very
view also... ) useful command for she
Options:
c:
display the number of
matching lines
e: match multiple patterns
i: ignore case of letters during
: display
comparisons
only filenames of files
containing a
pattern
n:
display output with line numbers
V: reverSe
matching; display
lines that do not contain
pattern
0: show pattern cach time it found
in a file
Examples:
grep "hello" 1est.1xt . Simple pattern matching
grep "manager" W,1xt ..
displays filenames having patterns
grep V "Mr." Customer.txt . reverse matching

8rep -e "Agarwal" -e "aggrawal" -"agrawal" emp.Ist


... multiple pattern matching

.0 Process Related: ps, time, kill, top


. ps

Process Status

Syntax: ps loptions

Usage: processes. By default, it shows the process ID


status of currently running
Displays the consumed by the process since it started, and the process

the associated terminal, the time


name or program name).
command
name (generally

Options: process TD) of cach process

showing the PPID (parent


f: full Iisting and system
processes
user
including
processes,
e or A: All
user
usr only
Processes
of
u usr information
memory-related

showing /dev/console)
1: long listing the
terminal
lerm, (say,
on
running
processes
t term:
Linux Operating System
144
2. time:
time Command 7 program
Syntax:
Usage: on the terminal.
time usage
command or program
and displays
EXecutes
three different time values:
in the form of
Here, time usage is displayed
command till its terminatin
invocation of the
) real time: total time from the
in the execution of itself,
actual time spent by a program
ii) user time:
the kernel doing work
on behalf of the user procese
ii) system time: time spent by
services to requests such as reading data from a
means providing
file stored on disk.

Examples:
time date

time SOrt - 0 newfile. lst emp.lst

3. kill:

Syntar: kill -signal] pid

Usage:
Sends a signal to a process.

By default, kills other process having process ID


pid.
Various signals, which can be sent to another
process, can be found with man neip
Examples:
kill 125 ..kills (terminates) process having ID 125.
kill -9 127 sends signal-9
..

(SIGKILL) to process 127.


4. top
Syntax: top loptions)]
Usage: Displays the current status ot the
system and a list of all nhing processes With
their usage information. running proces
Options:
n: displays 'n iterations before
ending
u: displays processes that
Delong to
specitfied user id or
Examples: user name

top 10
..displays output till 10
top -

root iterations
...displays all
processes invoked by user root
Linux Basics

,7
do,
thers: su, sude
logname, hostname, 145
Su:
exit, expr, tee, set
Switch User
Syntax: Su

Usage : AllOws to run


username]
shell as
another user usernane. There
for the username. will be a need to en ter a pass otd
Examples:
Su
Ser
running the command
temporarily becomes root il the correct
root
SS password is provided.
SU user2
a .user
running the command becomes user2
temporarily if the correct
password of user2 is
provided.
2 sudo:

Super User DO
Syntax: Sudo Command
Usage : Runs command with higher privileges like a super user. Used to perform restricted
operations.
Examples:
sudo reboot ...asks a user to enter a password and then allows reboot to execute,
which may not be possible without sudo.
3. logname:

Syntax: logname
Usage:
Displays the name of the current user.

that of who am i
The output will be the Same as

4 hostname:
Syntax: hostnamne

Usage: 201
hostname of the computer.
Displays the attached to the network.
name given tO the computer and
A hostname is a

5. exit:

Syntax: exit n)
Usage: closes terminal.
current shell und
Terminates
current code block like a loop or from
from the
useful to exit
If used in a shell script,

a program.
error.
exit with some
Options: lt zero,
normal exit. It non-zer0,

status.
n specifies exit

LAnux Oper. Sys./ 2022/ 19

You might also like