KEMBAR78
OS Notes Unit-1 | PDF | Operating System | Kernel (Operating System)
0% found this document useful (0 votes)
5 views22 pages

OS Notes Unit-1

The document provides an overview of operating systems, including their definitions, types, services, and structures. It discusses various OS types such as batch, multi-tasking, and real-time systems, along with their functionalities and system calls. Additionally, it covers the architecture of operating systems, including layered, monolithic, and microkernel structures, and includes a case study on UNIX and Windows operating systems.

Uploaded by

preethinaveen22
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views22 pages

OS Notes Unit-1

The document provides an overview of operating systems, including their definitions, types, services, and structures. It discusses various OS types such as batch, multi-tasking, and real-time systems, along with their functionalities and system calls. Additionally, it covers the architecture of operating systems, including layered, monolithic, and microkernel structures, and includes a case study on UNIX and Windows operating systems.

Uploaded by

preethinaveen22
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 22

23CSN102 OPERATING SYSTEMS

UNIT I INTRODUCTION

Concept of Operating Systems, OS Services, System Calls, Structure of an OS - Layered, Monolithic,


Microkernel Operating Systems, Case study on UNIX and Windows Operating System. Korn Shell
Programming: Basic Script Concepts, Expressions, Decisions: Making Selections, Repetition, Special
Parameters and Variables, Changing Positional Parameters, Argument Validation, Debugging Scripts.

OS Concepts
Define Operating System.
Definition1:
An Operating System (OS) is an interface between a computer user and computer
hardware. It is a software that enables applications to interact with a computer's
hardware.
Definition2
An operating system (OS) is system software that manages computer hardware, software
resources, and provides common services for computer programs.:
Kernel
The software that contains the core components of the operating system is called the kernel.

Types of Operating System

1. Batch Operating System


Batch OS was prevalent in the early days of computing, primarily on mainframe computers. It
is designed for processing tasks in batches without direct user interaction. Users submit jobs to
the system, which are then executed one after the other. These systems are efficient for
repetitive and resource-intensive tasks, such as payroll processing or large-scale data analysis.
2. Multi-programming System
Multi-programming OS takes a step forward in efficiency by allowing multiple programs to be
loaded into memory simultaneously. While one program is waiting for input/output operations
or other delays, the CPU can execute another program. This approach optimises CPU usage
and minimizes idle time, resulting in improved overall system performance.
3. Multi-Processing System
Multi-processing OS take advantage of multiple central processing units (CPUs) within a
single computer. These systems can distribute tasks across multiple CPUs, allowing for true
parallel processing. This approach significantly enhances computing power and is commonly
found in servers, high-performance workstations, and supercomputers.
4. Multi-Tasking OS
Multi-tasking OS is designed for personal computers and workstations, allowing users to run
multiple applications simultaneously. Each application runs as a separate process, and the OS
manages the allocation of CPU time to each process. Users can switch between applications
seamlessly, making efficient use of system resources.
5. Time-Sharing OS
Time-sharing OS takes multitasking to the next level by dividing CPU time among multiple
users. Each user is provided with a time slice or quantum during which their program runs.
This creates the illusion of each user having a dedicated machine, even on systems shared by
many users. Time-sharing is a hallmark of interactive computing, enabling tasks like text
editing, data entry, and online communication.
6. Distributed OS
Distributed OS is designed for networked computing environments where multiple computers
are interconnected. These systems manage resources across multiple machines, allowing users
to access files and services from different locations. They enhance collaboration and resource
sharing, making them suitable for modern enterprise networks and cloud computing.
7. Network OS
Network OS optimises network resources and facilitates communication in networked
environments. They are commonly used in server-client architectures, where multiple
computers connect to a central server. Network OS manages user access, file sharing, and data
communication across the network. You can also look at the rise of edge computing when
learning about network OS.
8. Real-Time Operating System (RTOS)
They are designed for applications that require precise and predictable response times. These
systems are commonly used in embedded systems, robotics, automotive control systems, and
industrial automation. RTOS prioritises tasks based on their deadlines, ensuring the timely
execution of critical operations.
9. Single-User, Single-Tasking OS
These operating systems are designed to support only a single user and allow them to perform
one task at a time. Examples include MS-DOS (Microsoft Disk Operating System) and early
versions of Apple's Macintosh operating system.
10. Single-user, Multi-Tasking OS
These operating systems enable a single user to perform multiple tasks simultaneously or in
parallel. They allow for efficient multitasking by dividing the processor's time among different
tasks. Examples include Microsoft Windows, macOS, and Linux distributions like Ubuntu.
11. Embedded OS
Embedded operating systems are lightweight and optimised for running on devices with
limited resources, such as smartphones, IoT devices, or embedded systems in cars or
appliances. They are designed for specific hardware architectures and often offer real-time
capabilities. Examples include Android Things, FreeRTOS, or Windows Embedded Compact.

12. Virtualisation OS
Virtualisation operating systems and hypervisors, allow multiple virtual machines (VMs) to
run on a single physical machine. They enable efficient resource sharing and isolation between
VMs, allowing for better utilisation of hardware resources. Examples include VMware ESXi,
Microsoft Hyper-V, and KVM.

OS Services

Following are a few common services provided by an operating system −


1. Program execution
2. I/O operations
3. File System manipulation
4. Communication
5. Error Detection
6. Resource Allocation
7. Protection

Program execution

Operating systems handle many kinds of activities from user programs to system programs like
printer spooler, name servers, file server, etc. Each of these activities is encapsulated as a
process.

A process includes the complete execution context (code to execute, data to manipulate,
registers, OS resources in use). Following are the major activities of an operating system with
respect to program management −
 Loads a program into memory.
 Executes the program.
 Handles program's execution.
 Provides a mechanism for process synchronization.
 Provides a mechanism for process communication.
 Provides a mechanism for deadlock handling.

I/O Operation

An I/O subsystem comprises of I/O devices and their corresponding driver software. Drivers hide
the peculiarities of specific hardware devices from the users.

An Operating System manages the communication between user and device drivers.
 I/O operation means read or write operation with any file or any specific I/O device.
 Operating system provides the access to the required I/O device when required.

File system manipulation

A file represents a collection of related information. Computers can store files on the disk
(secondary storage), for long-term storage purpose. Examples of storage media include magnetic
tape, magnetic disk and optical disk drives like CD, DVD. Each of these media has its own
properties like speed, capacity, data transfer rate and data access methods.

A file system is normally organized into directories for easy navigation and usage. These
directories may contain files and other directions. Following are the major activities of an
operating system with respect to file management −
 Program needs to read a file or write a file.
 The operating system gives the permission to the program for operation on file.
 Permission varies from read-only, read-write, denied and so on.
 Operating System provides an interface to the user to create/delete files.
 Operating System provides an interface to the user to create/delete directories.
 Operating System provides an interface to create the backup of file system.

Communication

In case of distributed systems which are a collection of processors that do not share memory,
peripheral devices, or a clock, the operating system manages communications between all the
processes. Multiple processes communicate with one another through communication lines in the
network.

The OS handles routing and connection strategies, and the problems of contention and security.
Following are the major activities of an operating system with respect to communication −
 Two processes often require data to be transferred between them
 Both the processes can be on one computer or on different computers, but are connected
through a computer network.
 Communication may be implemented by two methods, either by Shared Memory or by
Message Passing.

Error handling

Errors can occur anytime and anywhere. An error may occur in CPU, in I/O devices or in the
memory hardware. Following are the major activities of an operating system with respect to error
handling −
 The OS constantly checks for possible errors.
 The OS takes an appropriate action to ensure correct and consistent computing.

Resource Management

In case of multi-user or multi-tasking environment, resources such as main memory, CPU cycles
and files storage are to be allocated to each user or job. Following are the major activities of an
operating system with respect to resource management −
 The OS manages all kinds of resources using schedulers.
 CPU scheduling algorithms are used for better utilization of CPU.

Protection

Considering a computer system having multiple users and concurrent execution of multiple
processes, the various processes must be protected from each other's activities.

Protection refers to a mechanism or a way to control the access of programs, processes, or users
to the resources defined by a computer system. Following are the major activities of an operating
system with respect to protection −
 The OS ensures that all access to system resources is controlled.
 The OS ensures that external I/O devices are protected from invalid access attempts.
 The OS provides authentication features for each user by means of passwords.

System Calls
 A system call is a method for a computer program to request a service from the kernel of
the operating system on which it is running.
 A system call is a method of interacting with the operating system via programs.
 A system call is a request from computer software to an operating system's kernel.
Why System calls?
There are various situations where you must require system calls in the operating system.
Following of the situations are as follows:

1. It is must require when a file system wants to create or delete a file.


2. Network connections require the system calls to sending and receiving data packets.
3. To read or write a file, you need to system calls.
4. To access hardware devices, including a printer, scanner, you need a system call.
5. System calls are used to create and manage new processes.

Types of System Calls

1. Process Control
2. File Management
3. Device Management
4. Information Maintenance
5. Communication

Process Control
Process control is the system call that is used to direct the processes. Some process control
examples include creating, load, abort, end, execute, process, terminate the process, etc.

File Management
File management is a system call that is used to handle the files. Some file management
examples include creating files, delete files, open, close, read, write, etc.
Device Management
Device management is a system call that is used to deal with devices. Some examples of device
management include read, device, write, get device attributes, release device, etc.

Information Maintenance
Information maintenance is a system call that is used to maintain information. There are some
examples of information maintenance, including getting system data, set time or date, get time or
date, set system data, etc.

Communication
Communication is a system call that is used for communication. There are some examples of
communication, including create, delete communication connections, send, receive messages,
etc.

Examples of Windows and Unix system calls


There are various examples of Windows and Unix system calls. These are as listed below in the
table:

Process Windows Unix

CreateProcess() Fork()
Process Control ExitProcess() Exit()
WaitForSingleObject() Wait()

CreateFile() Open()
ReadFile() Read()
File Manipulation
WriteFile() Write()
CloseHandle() Close()

SetConsoleMode() Ioctl()
Device Management ReadConsole() Read()
WriteConsole() Write()

GetCurrentProcessID() Getpid()
Information Maintenance SetTimer() Alarm()
Sleep() Sleep()

CreatePipe() Pipe()
Communication CreateFileMapping() Shmget()
MapViewOfFile() Mmap()

Protection SetFileSecurity() Chmod()


InitializeSecurityDescriptor() Umask()
SetSecurityDescriptorgroup() Chown()

Generic Structure of an OS:


An operating system is a structure that allows the user application programs to interact with the
system hardware. Since the operating system is such a complex structure, it should be created
with utmost care so it can be used and modified easily.

Simple Structure

There are many operating systems that have a rather simple structure. These started as small
systems and rapidly expanded much further than their scope. A common example of this is MS-
DOS. It was designed simply for a niche amount for people. There was no indication that it
would become so popular.
z

It is better that operating systems have a modular structure, unlike MS-DOS. That would lead to
greater control over the computer system and its various applications. The modular structure
would also allow the programmers to hide information as required and implement internal
routines as they see fit without changing the outer specifications.

Layered Structure

One way to achieve modularity in the operating system is the layered approach. In this, the
bottom layer is the hardware and the topmost layer is the user interface.

As seen from the image, each upper layer is built on the bottom layer. All the layers hide some
structures, operations etc from their upper layers.

One problem with the layered structure is that each layer needs to be carefully defined. This is
necessary because the upper layers can only use the functionalities of the layers below them.
Advantages

Following are advantages of a layered operating system structure.


 High Customizable - Being layered, each layer implmentation can be customized easily.
A new functionality can be added without impacting other modules as well.
 Verifiable - Being modular, each layer can be verified and debugged easily.

Disadvantages

Following are disadvantages of a layered operating system structure.


 Less Performant - A layered structured operating system is less performant as compared
to basic structured operating system.
 Complex designing - Each layer is to planned carefully as each layer communicates with
lower layer only and a good design process is required to create a layered operating
system.

Monolith Structure

In monolith structured operating system, a central piece of code called kernel is responsible for
all major operations of an operating system. Such operations includes file management, memory
management, device management and so on. The kernal is the main component of an operating
system and it provides all the services of an operating system to the application programs and
system programs.

The kernel has access to the all the resources and it acts as an interface with application
programs and the underlying hardware. A monolithic kernel structure promotes timesharing,
multiprogramming model and was used in old banking systems.

Advantages

Following are advantages of a monolith operating system structure.


 Easy Development - As kernel is the only layer to develop with all major functionalities,
it is easier to design and develop.
 Performance - As Kernel is responsible for memory management, other operations and
have direct access to the hardware, it performs better.
Disadvantages

Following are disadvantages of a monolith operating system structure.

 Crash Prone - As Kernel is responsible for all functions, if one function fails entire
operating system fails.
 Difficult to enhance - It is very difficult to add a new service without impacting other
services of a monolith operating system.

Micro-Kernel Structure

As in case monolith structure, there was single kernel, in micro-kernel, we have multiple kernels
each one specilized in particular service. Each microkernel is developed independent to the other
one and makes system more stable. If one kernel fails the operating sytem will keep working
with other kernel's functionalities.

Advantages

Following are advantages of a microkernel operating system structure.

 Reliable and Stable - As multiple kernels are working simultaneously, chances of failure
of operating sytem is very less. If one functionlity is down, operating system can still
provide other functionalities using stable kernels.
 Maintainability - Being small sized kernels, code size is maintainable. One can enhance
a microkernel code base without impacting other microkernel code base.
Disadvantages

Following are disadvantages of a microkernel operating system structure.


 Complex to Design - Such a microkernel based architecture is difficult to design.
 Performance Degradation - Multi kernel, Multi-modular communication may hamper
the performance as compared to monolith architecture.

Case study on UNIX and Windows Operating System

What is UNIX Operating System?

The UNIX operating system is a set of programs that link the computer and the user. UNIX
operating system was created in the 1960s and has been updated continuously since then.
It is a powerful multi-user, multitasking OS created by AT&T Bell Laboratories. It is quite
popular among scientists, engineers, and academics because of its most valued properties such as
flexibility, portability, network capabilities, etc. It is a stable, multi-user, multitasking system for
servers, PCs, and laptops.
It is written in the C language, enabling the UNIX operating system to operate on various
platforms.
UNIX operating system comes with a Command Line Interface (CLI). UNIX knowledge is
required for actions that aren't covered by graphical software or when there isn't a window
interface available, such as during a telnet session.
Advantages

1. Many large online stores operate their websites on UNIX or Linux servers. It has also
been used to control mobile phones and other electronic devices.
2. It consumes less memory when running complicated programs. It may handle the virtual
memory very effectively. The virtual memory grows as many programs come into the
main memory. In UNIX, most of the jobs are completed with fewer resources.
3. The UNIX operating system is both free and safe, so it is commonly used by web hosting
providers. Domain Name Server (DNS), Dynamic Host Configuration Protocol
(DHCP), and the webserver are all tools used by many web hosting servers.
4. It allows you to open many programs, and all the programs execute in parallel using
multiprocessor technology.

Disadvantages

1. For UNIX, there is no proper documentation available. If the user has an issue, he must
seek the advice of an expert, as obtaining online assistance from the documentation is
quite difficult.
2. UNIX commands are far more difficult to learn than Windows, MS-DOS, and macOS.
3. It is difficult to use for new users. Because most UNIX work is done with commands in
the CLI, beginners must learn various commands. It is designed exclusively for
programmers, not for new users. Some users with a lot of experience have trouble
utilizing the commands since the names of some commands are extremely different.
4. Most of the UNIX commands use cryptic words. It's tough for a non-technical user to
grasp how commands work. Some commands use unusual characters, and it may be
difficult for new programmers to grasp them.
5. The user interface of the UNIX operating system is not attractive.
6. Some variants of UNIX need most memory usage.

What is Windows Operating System?


Windows is an operating system that was designed and developed by Microsoft Cooperation. It
is one of the most famous OSs around the world.

Windows uses a Graphical User Interface (GUI). It allows the users to store files, watch
videos, run software, play games, and access the Internet. The first version of Microsoft
Windows is version 1.0 that was released on November 10, 1983.

Microsoft Windows comes in various versions, including Windows XP, Vista, Windows 95,
Windows 7, 8, 10, and 11.

The first business-oriented Windows version, known as Windows NT 3.1, was introduced
in 1993. The next versions, Windows 3.5, 4/0, and Windows 2000, were released.

Microsoft created the various versions of Windows XP for home and the commercial
environment when it was released in 2001.

It was built using common x86 hardware, like AMD and Intel processors. Therefore, it may run
on different hardware, including HP, Dell, Sony systems, and custom-built PCs.

Advantages

1. The Windows platform is suitable for game and software developers. Because Windows
has a large user base, so designers want to create utilities, games, and programming for
the operating system.
2. Windows 10 is intended for use on both touch-screen devices and desktop systems.
Windows 10's user interface is meant to operate better with a Windows gadget.
3. As the Windows operating system is used by 95% of users, most equipment merchants
create drivers for Windows.

Disadvantages

1. Most of Windows's products are paid, such as design programming, games, download
chief, and another popular programming. Users must purchase these products or pay a
monthly charge to use them.
2. Linux operating system is open-source and free to use for anyone, but Windows requires
a purchased license and cannot be used for free. Windows operating system is also
expensive. You'll also need to purchase other Microsoft software, such as MS Office, to
do regular office work on the system.
3. Windows have a high amount of hacker attacks. Hackers may easily crack Windows
security. As a result, Windows users are relying on anti-virus software and must pay
monthly charges to firms to secure their data. In addition, Windows users must keep their
operating systems up to date in order to receive security fixes.
4. Windows operating system support is not ideal for most users. Only a few significant
enterprises may rely on the Windows team for assistance. Common users must look for
forums to fix their problems.
5. To install Windows, the computer will have plenty of RAM, lots of good hard drive
space, and a good graphics card. It is due to the features used in Windows. If you wish to
install graphics applications, such as Photoshop, you should have at least 16 GB of RAM.

What is a Shell?
Def: A shell is a type of computer program called a command-line interpreter that lets Linux and
Unix users control their operating systems with command-line interfaces. Shells allow users to
communicate efficiently and directly with their operating systems.

Def2: A shell is a special user program that provides an interface for the user to use operating
system services. Shell accepts human-readable commands from users and converts them into
something which the kernel can understand. It is a command language interpreter that executes
commands read from input devices such as keyboards or from files.

Korn Shell

Korn Shell, also known as ksh, is a Unix shell that was developed by David Korn in the early
1980s.

Features of Korn shell (ksh):


 Job Control: Korn shell provides extensive support for job control, which allows you to
manage and manipulate running processes.
 Advanced I/O Redirection: Korn shell allows you to perform advanced I/O redirection,
such as redirecting output to a file while still displaying it on the screen.
 Command Line Editing: Korn shell provides command line editing features that allow you
to edit and modify previously entered commands.
 Arithmetic Evaluation: Korn shell has built-in support for arithmetic evaluation, allowing
you to perform mathematical calculations directly within the shell.
 Variables: Korn shell supports variables and parameter expansion, which allow you to
manipulate and modify variables within the shell.

Basic Script Concepts


General commands
Command with Function
syntax
date Used to display the current system date and time.
date +%D Displays date only
date +%T Displays time only
date +% Y Displays the year part of date
date +% H Displays the hour part of time
cal Calendar of the current month
cal year Displays calendar for all months of the specified year
cal month year Displays calendar for the specified month of the year
who Login details of all users such as their IP, Terminal No, User
who am i Used to display the login details of the user
tty Used to display the terminal name
uname Displays the Operating System
uname –r Shows version number of the OS (kernel).
uname –n Displays domain name of the server
echo "txt" Displays the given text on the screen
echo $HOME Displays the user's home directory
bc Basic calculator. Press Ctrl+d to quit
lp file Allows the user to spool a job along with others in a print
man cmdname Manual for the given command. Press q to exit
history To display the commands used by the user since log on.
exit Exit from a process. If shell is the only process then logs out
Directory commands
Command with Function
syntax
pwd Path of the present working directory
mkdir dir A directory is created in the given name under the current
mkdir dir1 dir2 A number of sub-directories can be created under one stroke
cd subdir Change Directory. If the subdir starts with / then path
starts from
cd To switch to the home directory.
cd / To switch to the root directory.

Command with Function


syntax
cd .. To move back to the parent directory
rmdir subdir Removes an empty sub-directory.
File commands
Command with Function
syntax
cat > filename To create a file with some contents. To end typing
press Ctrl+d. The > symbol means redirecting output to
cat filename Displays the file contents.
cat >> filename Used to append contents to a file
cp src des Copy files to given location. If already exists, it will be
cp –i src des overwritten
Warns the user prior to overwriting the destination file
cp –r src des Copies the entire directory, all its sub-directories and files.
mv old new To rename an existing file or directory. –i option can also
mv f1 f2 f3 dir To move a group of files to a directory.
mv –v old new Display name of each file as it is moved.
rm file Used to delete a file or group of files. –i option can also
rm * be
To used
delete all the files in the directory.
rm –r * Deletes all files and sub-directories
rm –f * To forcibly remove even write-protected files
ls Lists all files and subdirectories (blue colored) in sorted
ls name To check whether a file or directory exists.
ls name* Short-hand notation to list out filenames of a specific
ls –a pattern.
Lists all files including hidden files (files beginning with
ls –x dirname To have specific listing of a directory.
ls –R Recursive listing of all files in the subdirectories
ls –l Long listing showing file access rights
(read/write/execute-rwx for user/group/others-ugo).
cmp file1 file2 Used to compare two files. Displays nothing if files are
wc file identical.
It produces a statistics of lines (l), words(w), and
chmod perm file characters(c).
Changes permission for the specified file. (r=4, w=2,
x=1) chmod 740 file sets all rights for user, read only
for groups and no rights for others

The commands can be combined using the pipeline (|) operator. For example, number of
users logged in can be obtained as.
who | wc -l
Filters
Filters are the central commands of the UNIX tool kit. It acts on data file where lines
are records, fields delimited by a character not used by the data (mostly |, default is white
space). The output is a set of records and the input file is unaltered by these commands.

Command Function
headʊused to display the first few records (10 records by default)
head stud Displays first 10 records by default
head -5 stud Displays first 5 records
head -1 stud | wc –c length of first record
tailʊused to display the last few records (10 records by default)
tail stud Displays last 10 records by default
tail -5 stud | tee last5 Last 5 records listed & stored in file last5 using
cutʊused to extract specific fields. The d option specifies the delimiter and
f for specifying the field list. The c option may be used if extraction is done
cut –d \| -f 1,3,4 stud Fields 1,3,4 listed
cut –d \| -f 2-4 stud Fields 2,3,4 listed
paste –d \| list1 list2 merges two cut files list1 and list2
sortʊreorders the file as per ASCII sequence. The t option is used to specify
sort stud Sorted on 1st column by default
sort –t \| +2 stud Sort as per 3rd column
sort –c stud Check if file is sorted using c option
sort –t \| +3 -4 +4 stud Sorting on secondary keys
sort -t \| -nr +4 stud Sort on numeric field using n option, r for
uniq stud Display unique entries in a sorted file
nlʊdisplay file content with lines numbered. The s option is used to specify
nl –s "|" stud Displays entries numbered with separator |
trʊtranslates characters. Can be used to change text case. It works with standard
tr '[a-z]' '[A-Z]' < stud Changes text to upper case

Operators & Expressions:


 Arithmetic Operators
 Relational Operators
 Boolean Operators
 String Operators

The following example shows how to add two numbers −

#!/bin/sh

val=`expr 2 + 2`
echo "Total value : $val"

The above script will generate the following result −

Total value : 4

The following points need to be considered while adding −


 There must be spaces between operators and expressions. For example, 2+2 is not
correct; it should be written as 2 + 2.
 The complete expression should be enclosed between ‘ ‘, called the backtick.

Arithmetic Operators

The following arithmetic operators are supported by Bourne Shell.

Assume variable a holds 10 and variable b holds 20 then −


Operator Description Example

+ (Addition) Adds values on either side of the operator `expr $a + $b` will give 30

- (Subtraction) Subtracts right hand operand from left hand operand `expr $a - $b` will give -10

`expr $a \* $b` will give


* (Multiplication) Multiplies values on either side of the operator
200

/ (Division) Divides left hand operand by right hand operand `expr $b / $a` will give 2

Divides left hand operand by right hand operand and


% (Modulus) `expr $b % $a` will give 0
returns remainder

a = $b would assign value


= (Assignment) Assigns right operand in left operand
of b into a

Compares two numbers, if both are same then [ $a == $b ] would return


== (Equality)
returns true. false.

Compares two numbers, if both are different then [ $a != $b ] would return


!= (Not Equality)
returns true. true.

It is very important to understand that all the conditional expressions should be inside square
braces with spaces around them, for example [ $a == $b ] is correct whereas, [$a==$b] is
incorrect.
All the arithmetical calculations are done using long integers.

Relational Operators

Bourne Shell supports the following relational operators that are specific to numeric values.
These operators do not work for string values unless their value is numeric.

For example, following operators will work to check a relation between 10 and 20 as well as in
between "10" and "20" but not in between "ten" and "twenty".
Assume variable a holds 10 and variable b holds 20 then −
Operato
Description Example
r

Checks if the value of two operands are equal or not; if yes,


-eq [ $a -eq $b ] is not true.
then the condition becomes true.

Checks if the value of two operands are equal or not; if


-ne [ $a -ne $b ] is true.
values are not equal, then the condition becomes true.

Checks if the value of left operand is greater than the value


-gt [ $a -gt $b ] is not true.
of right operand; if yes, then the condition becomes true.

Checks if the value of left operand is less than the value of


-lt [ $a -lt $b ] is true.
right operand; if yes, then the condition becomes true.

Checks if the value of left operand is greater than or equal


-ge to the value of right operand; if yes, then the condition [ $a -ge $b ] is not true.
becomes true.

Checks if the value of left operand is less than or equal to


-le the value of right operand; if yes, then the condition [ $a -le $b ] is true.
becomes true.

It is very important to understand that all the conditional expressions should be placed inside
square braces with spaces around them. For example,
[ $a <= $b ] is correct whereas, [$a <= $b] is incorrect.

Boolean Operators

The following Boolean operators are supported by the Bourne Shell.

Assume variable a holds 10 and variable b holds 20 then −


Operato
Description Example
r

This is logical negation. This inverts a true


! [ ! false ] is true.
condition into false and vice versa.

This is logical OR. If one of the operands is true,


-o [ $a -lt 20 -o $b -gt 100 ] is true.
then the condition becomes true.
This is logical AND. If both the operands are true,
-a [ $a -lt 20 -a $b -gt 100 ] is false.
then the condition becomes true otherwise false.

String Operators

The following string operators are supported by Bourne Shell.

Assume variable a holds "abc" and variable b holds "efg" then −


Operato
Description Example
r

Checks if the value of two operands are equal or not; if


= [ $a = $b ] is not true.
yes, then the condition becomes true.

Checks if the value of two operands are equal or not; if


!= [ $a != $b ] is true.
values are not equal then the condition becomes true.

Checks if the given string operand size is zero; if it is


-z [ -z $a ] is not true.
zero length, then it returns true.

Checks if the given string operand size is non-zero; if it


-n [ -n $a ] is not false.
is nonzero length, then it returns true.

Checks if str is not the empty string; if it is empty, then


str [ $a ] is not false.
it returns false.

Selection (conditional Statements)


Conditional Statements: There are total 5 conditional statements which can be used in bash
programming
 if statement
 if-else statement
 if..elif..else..fi statement (else if ladder)
 if..then..else..if..then..fi..fi..(Nested if)
 switch statement
if statement
This block will process if specified condition is true.
Syntax:
if [ expression ]
then
statement
fi
if-else statement
If specified condition is not true in if part then else part will be executed.
Syntax
if [ expression ]
then
statement1
else
statement2
fi
if..elif..else..fi statement (else if ladder)
To use multiple conditions in one if-else block, then elif keyword is used in shell. If expression1
is true then it executes statement 1 and 2, and this process continues. If none of the condition is
true then it processes else part.
Syntax
if [ expression1 ]
then
statement1
statement2
.
.
elif [ expression2 ]
then
statement3
statement4
.
.
else
statement5
fi
if..then..else..if..then..fi..fi..(Nested if)
Nested if-else block can be used when, one condition is satisfies then it again checks another
condition. In the syntax, if expression1 is false then it processes else part, and again expression2
will be check.
Syntax:
if [ expression1 ]
then
statement1
statement2
.
else
if [ expression2 ]
then
statement3
.
fi
fi
switch statement
case statement works as a switch statement if specified value match with the pattern then it will
execute a block of that particular pattern
When a match is found all of the associated statements until the double semicolon (;;) is
executed.
A case will be terminated when the last command is executed.
If there is no match, the exit status of the case is zero.
Syntax:
case in
Pattern 1) Statement 1;;
Pattern n) Statement n;;
esac
Example Programs
Example 1:
Implementing if statement
#Initializing two variables
a=10
b=20

#Check whether they are equal


if [ $a == $b ]
then
echo "a is equal to b"
fi

#Check whether they are not equal


if [ $a != $b ]
then
echo "a is not equal to b"
fi
Example 2:
Implementing if.else statement
#Initializing two variables
a=20
b=20

if [ $a == $b ]
then
#If they are equal then print this
echo "a is equal to b"
else
#else print this
echo "a is not equal to b"
fi
Example 3:
Implementing switch statement
CARS="bmw"
case "$CARS" in
#case 1
"mercedes") echo "Headquarters - Affalterbach, Germany" ;;
#case 2
"audi") echo "Headquarters - Ingolstadt, Germany" ;;
#case 3
"bmw") echo "Headquarters - Chennai, Tamil Nadu, India" ;;
esac

Repetion (Looping) Statements in Shell Scripting:


There are total 3 looping statements that can be used in bash programming
1. `while` statement in Shell Script in Linux
Syntax:
while <condition>
do
<command 1>
<command 2>
<etc>
done
Example
a=0
while [ $a -lt 10 ]
do
# Print the values
echo $a
# increment the value
a=`expr $a + 1`
done

2. `for` statement in Shell Script in Linux


Syntax:
for <var> in <value1 value2 ... valuen>
do
<command 1>
<command 2>
<etc>
done

3. `until` statement in Shell Script in Linux

The until loop is executed as many times as the condition/command evaluates to false. The
loop terminates when the condition/command becomes true.

Syntax:
until <condition>
do
<command 1>
<command 2>
<etc>
done
Example
a=0
until [ $a -gt 10 ]
do
echo $a
a=`expr $a + 1`
done

To alter the flow of loop statements, two commands are used they are,
1. break
2. continue

You might also like