Os Material
Os Material
Memory Management :-
When you start a program, OS retrieves it from permanent disk & loads into main
memory (RAM).
Before loading OS checks whether enough memory space is there or not i.e. two parts :
1. Memory allocation
2. Memory deallocation
1)Memory Allocation:
Memory allocation is the act of managing computer memory. In its simpler
forms, this involves providing ways to allocate portions of memory to programs at their request,
2) Memory Deallocation:
Freeing memory for reuse when no longer needed. The management of main
memory is critical to the computer system.
CPU Management :-
OS helps CPU to schedule its activities so as to meet demand of various part of
computer because CPU is needed by more than one program / resource.
Disk Management :-
It Manages the secondary storage devices
OS helps to store & retrieve file whenever required.
User need not to bother about how & where data or files are stored & how to find them.
User Interface :-
Gap between machine language and human readable language is solve with the help of
OS.
creates an easy & interactive interface between user and computer using command
interpreter.
Command Interpreter helps user to interact with Operating System.
Security Management:-
It ensure data security and integrity.
It keeps different data and program in memory in such a manner that it do not
interface with each other.
Processor Management:-
OS assign processor to different task that must be performed by computer
system.whenever OS find the processor idle it assign job to the processor.
The main feature of processor management is that to ensure that program or
a process is run on each processor at all time.
Various Types of OS
when batch of program have been collected, operator load this batch of program
into computer.
ADVANTAGES :-
After I/p process is over, while processing is going on user can attend other jobs.
This Operating System is less complicated.
DISADVANTAGES :-
Difficult to provide priority Scheduling.
Turn around time is very long.
Access to one program is not possible.
It is not convenient for program development.
If result of particular program or time detail are required,you have to wait till entire
batch is processed.
OS which handles more than one program in main memory at a time is known as
Multiprogramming OS.
In fig.
Supervisor
Waiting Prog A
Prog B
O/P Data Prog C
(waiting for
CPU)
The main advantage of this Operating system is CPU can allocate time to several programs
instead of remaining idle when one program is busy with I/O Operations.
In this Operating system all program appear to be processed simultaneously but actually each
program get turn for executing I,e at any time only one of the program has control of CPU and
executing the instruction.
ADVANTAGES :-
Many programs can run simultaneously.
Time is not wasted in switching from one program to another.
Maximum utilization of resources.
Important & short jobs need not wait for batch.
DISADVANTAGES :-
OS is complicated because many program are handled together.
Job of resource management & memory management increases.
Large main memory required.
Multiprocessor System :-
The Multiprocessor Operating system is called Multiprocessor because it make use of more
than one CPU.
the term multiprocessor is computer with 2 or more CPU‟s that have ability to simultaneously
execute several programs.
In this Operating System different program can process at the same time by different CPU.
In case of failures of one CPU, the other takes over complete workload until repair are made.
There are more than one program in main memory at a time.
The basic organization of typical multiprocessing system is shown in fig given below:
CPU 1 Main Mem. CPU 2
Instead of one CPU,computer has two or more CPUs I,e more than one program is executed in
Operating system at a time.
This is needed when maximum program running on your computer are likely to need CPU.
ADVANTAGES :-
Improve the performance by allowing parallel processing of programs.
Turnaround time of this system is less.
In case of failure of one CPU other CPU can take over the total workload without
any loss. .
More efficient utilization of CPU & other devices of computer.
DISADVANTAGES :-
OS is more complicated because multiple program and processor are handled
together.
A large main memory required.
It is very expensive.
Time Sharing OS :-
User 3 User 3
User 4 User 4
Wait Wait
Wait Wait
The main objectives of time shairing OS provide fast response time to each user of computer.
In this OS CPU is divided into user on a schedule basis.
It allows all user program to gets a brief share of CPU in turn.
Each user program,starting from first till last user has allocated a short period of CPU time to
all users.
A short period of time during which user can get attention of the CPU is known as „a time slice‟
or „time slot‟ and it is in order of 10 to 100 milliseconds.
In this OS,only one program can be in the control of CPU at given time like Multiprogramming
OS.
It is not possible to keep progam of all user simultaneously in main memory because of limited
main memory.
The time shairing Operating System keeps only few programs in main memory and rest of the
program are stored on disk storage.
Main features of Time shairing OS are as follows:
1) Processing time are divided into various program called time slice.
2) Each program is given the CPU time one by one.
3) Shairing of only one CPU by different user simultaneously.
ADVANTAGES :-
Turn around time is negligible.
Computing cost is very less.
All programs get equal attention & small program get over fast.
Reduce CPU idle time.
Avoids duplication of s/w.
DISADVANTAGES :-
OS is more complicated.
Question of security: Hundred of users are using the system simultaneously so
provision of security is provided.
Problem of Data Communication:In this system user communicate with main
computer through remote terminals that requires data communication facilities.
ADVANTAGES :-
Turn around time is negligible.
Access & retrieval of record is quick direct.
DISADVANTAGES :-
OS is complicated & costly.
Question of security.
Data transmission facility required.
i.e. in OS user interact with main computer system through remote terminal
that require data comm. facilities.
Real Time Processing :-
A system in which a transaction access & updates a file quickly enough to affect the original
decision-making is called Real time system.
This Operating System is used where immediate response from computer requires.
Eg – stock market.
Real time use online processing but online system need not operate in real time mode.
Real time OS should be highly reliable because a small problem can be lead into fatal accident
and to achieve reliability, Real time OS should be duplicated so that,at the time of breakdown
,backup facilities are immediately for continious operation of system.
ADVANTAGES :-
Response time is very less.
Data processing is very fast.
DISADVANTAGES :-
A complicated system.
Very expensive.
APPLICATIONS :-
Air traffic control system.
In Chemical process control system
In Control satellite operation.
Chapter : 2 PROCESS
Introduction to Process :-
Process is nothing but it is a program in execution i,e it can be defined as a program currently
making use of processor at any time.
Execution of user program in Multiprogramming or Time Shairing System is represented by set
of processes.
Interaction between process involves Shairing or Exchanging data or messages and control
signals.
Process is made up of a tuple
Tuple consist of process id, code, data, register value, PC value where,
1) process id is unique id in system which is assign to process.
2) Code is a program code.
3) Data is data used during its execution i.e. initialization & un-initialization.
4) Register values is value in machine registers.
5) PC is address in program counter i.e. starting address of program.
At the moment only one process is actively executing which is given to CPU.
Other process are in 2 state of suspension, when interrupt arise, the process executing on CPU
is suspended.
After interrupt is processed, OS instruct the scheduler, which select one process for execution
on CPU.
Note that process is sequential in nature i,e instruction in program code is executed one after
another.
Example:- Following process exist in an OS.
Process P1: (P1,C1,D1,rv1,Pc1)
P2: (P2,C2,D2,rv2,Pc2)
P1: (P3,C1,D3,rv3,Pc3)
Process State :-
Process state is used by OS to simplify process scheduling.
Process Pi is said to be in state Si. The four fundamental state for process are.
Running State :-
A CPU is currently allocated to process & process is in execution.
Blocked State :-
A process is waiting for a request to be satisfied, i.e. process cannot
execute even if CPU is available.
Ready State :-
The process is not running however it can execute if a CPU is
allocated to it (i.e. process is not blocked)
Terminated State :-
The process has finished its execution.
A state transition is a change from one state to another.
Process state is change by occurrence of some event in system.
Fig:
Terminate
Running
Ready Blocked
When a process is in a running state makes a request of I/O it has to enter the block state
waiting till completion of I/O
After completion of I/O, process state changes from blocked to ready.
A ready process becomes running when CPU is allocated to it.
OS maintains a list of process in ready state. This list is called the Processed Scheduling list.
The scheduler picks one process from list & allocates CPU to it.
Note that the state of process is the function of two component.
1. Recent behaviour of process.
2. Occurrence of event pertaining to it.
Process id
Priority
Process state
PSR (Process state
Register)
Registers
Event Information
Memory Allocation
Resources held
PCB Pointer
The PSR and Machine register field represent a snapshot of CPU when it is released by the
process.
When a process is scheduled once again yhis information from its PCB can simply be loaded
into processor to resume its execution.
Event information field of PCB plays an important role in effecting appropriate state transition
in system.
Process Scheduling :-
Process Scheduling is impotant feature of OS which determine which request should be
service.
It is fundamental OS function which involves following task:
1. Creating new process.
2. Monitoring process status.
3. Selecting process for execution (Process Scheduling).
4. Allocating CPU to selected process (Process Dispatcher).
5. Deallocating CPU from process and determine new state of process (Process
preemption)
6. Termination of process.
7. Supporting communication and synchronization request of process.
8. Interfacing with other OS modules which affect process state.
Almost all computer resources are schedule before use.
The process scheduling component consist of 3 smaller component.
1. Event handler.
2. Process Schedular.
3. Process Dispatcher.
Fig:-
Command interpreter job handler event handler process dispatcher
PCB
Job scheduler
Process schedular
Process scheduler examines the information in PCBs to select a process for execution
and hands over its PCB to dispatcher. The dispatcher loads the PSR and register
contents from PCB into CPU to initiates execution of process.
Event handler process each interrupt occurring in system,determines the event causing
the interrupt and logs an application change of state in PCB of affected process.
SCHEDULING:-
Completion:-
When a processing of request get completed Scheduling is performed to select
another request for processing.
Fig:-
Preempted request
Arriving request
Scheduled
P1 24
P2 3
P3 3
- If process arrives in order P1, P2, P3 & served in FCFS manner as shown in Gantt
Chart.
P1 P2 P3
0 24 27 30
- The waiting time is 0 ms for P1
24 ms for P2
27 ms for P3
3) Priority Scheduling :-
- In priority scheduling a priority is associated with each process & CPU is allocated
to the process with highest priority.
- A SJF algorithm is a priority algorithm where a large CPU burst, lower the priority.
- In priority scheduling priorities are generally from some fixed range of numbers
such as 0 to 7or 0 to 350.
- There is no arrangement on whether zero is highest or lowest priority.
- Some system use low no to represent low priority, other mayuse low number for
high priority.
- Consider the following, set of process. Assume that the arrival time is zero. Order is
P1, P2, P3, P4, P5 with the length of CPU burst time given in minutes.
P2 P5 P1 P3 P4
0 1 6 16 18 19
= 8.2 minutes
5
- Priorities can be defined either internal or external.
- Internal priorities use some measure to compute priority of process
Eg – time limits, memory requirements, number of open file & ratio of I/O
operation.
- External priorities are set by criteria that are external to OS such as importance of
the process etc.
- Can be either preemptive / non-preemptive when a process arrives at the ready
queue, its priority is compared with the priority of currently running process
(preemptive)
- Non-preemptive priority scheduling algorithm will simply put a new process at the
head of ready queue.
- Major drawback is in-definite blocking or starvation.
- A priority-scheduling algorithm can leave some low priority process waiting indefinitely for
CPU in highly loaded system.
- Solution of indefinite blocking of low priority is aging.
- Aging is a technique of gradually increasing the priority of processes that is waiting
for long time.
- time quntum=4ms.
P1 P2 P3 P1 P2 P3 P1 P3 P3
0 4 8 12 16 17 21 23 27 30
- main advantage of this scheduling is the time quantum is given to each process and
process is terminated then the time quantum is given to next and so on and CPU time is
allocated to each process in circular manner.
- Performance depends upon size of time quantum.
MULTIPROCESSING OS
- The operating system more than one processor (CPU) is multiprocessing OS, which shares
a computer bus, the clock & some time memory & peripheral devices.
- Advantage of multiprocessing Operating System is increase the throughput by increasing
the number of processor to get more work done in shorter period of time.
- Increase reliability i.e.If CPU fails then another CPU can take the total workload of failure
CPU.
MULTITASKING OS
- Multitasking Operating System allows more than one job / task at the same time on a
computer.
- Operating System such as windows 9x, Unix, Linux, etc. support multitasking.
Eg – when you open MS Word & Internet Explorer at the same time Windows OS is doing
multitasking.
- There are two modes in multitasking, background & foreground.
MULTITHREADING OS
It is a technique in which process,execution and application is divided into threads that
can be run concurrently.
Multithrading is useful for application that performs a number of essentially
independent task that do not need to be serialized.
Multithreading computer have h/w support to efficiently execute ultiple threads.
These are differentiate from multiprocessing system in that the threads must operate in
the same address space,as there is only one shared set of CPU cache and one Translation
Look aside buffer (TLB).
Some critism of Multithreading Includes:
1. Multiple threads can interface with each other when shairing h/w
resources such as Cache ot Translation Look aside buffer (TLBs).
2. Execution time of single thread are not improved but can be degraded.
3. H/W technique use to support multithreading often parallel the s/w
technique used for computer multitasking of computer program.
Chapter : 3 MEMORY MANAGEMENT
Introduction:
The memory hierarchy of a computer system consist of secondary memories like disks and
tapes,the primary memory (i,e RAM),and buffer or cache memories. Of these, management of
secondary memory is under the control of file system.
OS responsibilities in memory management include memory allocation and memory
deallocation,efficient utilization of memory and protection of memory allocated to a program or
process from interference by other programs or process.
Two types of memory management are performed during the operation of OS.These involves
memory allocation and deallocation.
1. to program or processes.
2. within a program or process.
Allocation to user program and process is performed by the kernel. This activity is
characterized by the fact that the program and process sizes vary over a wide range of values.
This makes efficient utilization of memory rather difficult.
Protection is very important issue in memory management as program and processes are
independent entities and have to be protected against mutual interferences.
Memory management means identifying the free memory space & reusing the memory space
by making memory allocation, deallocation & effectively use of memory utilization.
Memory management in operating system is management of the primary memory.
Memory management in Operating System includes,
1) Memory protection
- Memory protection is used to avoid interference between program existing in
memory.
- Implementation of memory protection requires support from machine
architecture in the form of memory bound registers or memory protection keys.
Fig:
memory
protection violation Multiprogram
LBR interrupt supervisor
privilege mode 200k Job1 200 K
k
Job2 250K
PSR Job m
UBR 250 k
Address 85,252 P3
According to figure During the execution of program its APK is put in the Memory Protection
Information (MPI) field of PSW.
P1‟s APK is 1.Hence memory blocked allocated to P1 have memory protection key „1‟ and the
MPI field of PSW contains „1‟ when P1 is in execution.
Consider an access to memory location with address 85,252. The memory protection h/w obtain
the protection key assign to memory block contains this address and compares it with values in
MPI. Since the values are different,a memory protection violation are raised.
a) Bound Register Scheme :-
i) While allocation of memory :-
- put the start of end address of memory area allocated to program
in the programs PCB.
ii) While dispatching :-
- Load PSR with content of relevant field of program PCB
o Definition
It is a system where, in logical address of instruction or data word is different
from physical address.
- ATU (Address Translation Unit)in system is used to translate a logical address in
logical address space of program into physical address.
- 2 fundamental approach to implementation VM are
1) Paging
2) Segmentation
- These two approach differ from each other by boundaries & size of program.
Fig:-
Block Other
Memory ATU
MR NO Nfo
15/ 479
Add / 15479 31
31 / 479
Virtual Memory Using Segmentation
Memory Compaction
- To eliminate external fragmentation, OS can periodically perform memory compaction.
- Produce a single unused area in memory.
- This memory / area may be large enough to accommodate one or more new program.
- Fig:
30 K A A A
44 K B C C
16 K C D D
24 K D 46 K E
48 K
4K 2K
Garbage Collection
- Garbage collection is selective reuse of memory fragements.
- When program terminates & release its allocation, OS searches through a list of program
waiting for memory allocation & select a program which is executed at that memory area.
- 2 criteria :
1) First fit criteria
2) Best fit criteria
- First fit criteria selects program which is executed in free area, i.e. first program with size
<= z (z = memory unit)
- Best fit find largest program with size < z this leads to smaller hole in allocation thus
reducing the amount of usable memory.
- Consider a system which has 170 Kbytes available for user program.
Let the following program await memory allocation.
-The 1st fit policy would initiate program C and D leading to total fragmentation of 40K bytes.
-The best fit policy would initiate program D and F leading to total fragmnentation of 10 K bytes.
-Fig:
Non Contiguous Memory Allocation
- To overcome the drawback of contiguous memory allocation (memory fragmentation) the
effective solution is Non Contiguous memory allocation.
Eg – checks how non contiguous allocation is use to avoid fragmentation.
- 4 unallocated memory area of 50, 30, 80 & 60k bytes exist in memory.
- Program p require a total of 140k bytes is loaded into three. P program part existing in these
different areas as P-1, P-2, P-3 respectively.
- Free memory area now exist in following parts P-3 & program D is memory. These area is
use to initiate another program of size <= 80k. This avoids external fragmentation.
- Since the program part P1, P2 & P3 in fig have the size of 50, 30 & 60 bytes, XYZ lies in
P2 & has memory address of say 212488.
- An instruction in P-1 uses the address 62 488 to access XYZ. This address should be
corrected to 212488. This is best done by h/w unit that is located on path of memory i.e. the
process of correcting an address is called address translation.
- The address of memory location where the operand is actually located is called as effective
memory address of operand.
- Figure shows program execution when non contiguous memory allocation model is used.
The arrow shows access of XYZ by instruction of program P.
- Dotted arrow shows how the access is actually implemented during an execution of P.
- ATU corrects the address of XUZ to point at actual memory where XYZ exist.
- ATU corrects each memory address generated by program in this manner.
50 P-1
10 K
(A)
Supervisor
(B)
Supervisor
(C)
Supervisor
F F
30 k
30 K A A A
44 K B C C
16 K C D D
Block Other
24 K Ready
I/O Proc
CP
Running
U1
Terminate
Blocked
Memory
I/O Proc
ATU
15/ 479
MR NO Nfo
46 K E
I/O Units I/O Units
31
Add / 15479
31 / 479
48 K
4K 2K
D
P-2
k C XYZ
C
80 k
20 k P-3 Addr = 22,488
D
60 k D
Chapter : 4 STARTING WITH UNIX
1) Kernel
Kernel is a hear of OS
It interacts with h/w & most of task like memory management, file management
etc, i.e. interaction with end user application shells etc.
Unix derives most of its functionality via kernel.
2) Shells
Shell is utility that process your request.
When you type in a command at your terminal, the shell interprets the command
& calls the program that you want.
Shell use standard syntax for all commands.
C shell, Bourne shell & kornshell are most famous shells, which are available
with all Unix.
Feature of Unix
- Some key features of Unix Architecture are as follows :
1) Unix system utilize a centralized OS kernel which manage system & process
activities
2) Unix system are multitasking
i.e. multiple process can run at the same time, or within a small time slice &
nearly at same time & that process is interrupted & moved out of execution by
kernel. This is known as thread management.
3) Files are arranged / stored on disk in hierarchical file system.
i.e. with a single top location throughout system (“root” or “/”) with both files &
directories, subdir, sub-subdir & so on, on below it.
Fig of Unix Architecture
Application
Program
ksh bash
sh
more
Text
Processor csh
ps
Mail
cpp which
H/W
cnv
comp
as cat
Kernal FTP
shell ed
DBMS vi
Types of Shells
There are different shells available in Unix. Most popular are as follows :
1) Bourne shell
2) Korn shell
3) C shell
- Shell means any program that user can use to type command.
- When user logs in to system shell program is automatically executed.
- The program is called shell because it hides the details of OS behind shell interface & manages
the technical details.
1) Bourne shell :-
- Bourne shell is one of the most important shell used in early version of Unix OS & becomes
a standard.
- It is written by Stephen Bourne in Bell labs.
- Bourne shell program name is sh & it is typically located in Unix file system hierarchy at
/bin/sh.
Features :-
1) Scripts can be invoked as commands by using their filename.
2) Provide set of built in commands
3) Provide flow control constructs, quotation facilities & functions.
4) Provide local & global variable scope.
5) Support I/O redirection & pipelines.
2) Korn shells :-
Korn shell is a Unix shell which was developed by David Korn in AT & T Bell labs in
1980.
- It includes many features of c shell such as command history.
- Main advantage of ksh over Unix shell is it is use as programming language.
- The kshg3 version support Associative array & built in floating point arithmetic.
- It is interactive command language that provides access to Unix system & to many other
systems, on many different computers & workstation on which it is implemented.
- Korn shell language is also complete, powerful, high level programming language for
writing application. (more easy & quick than other HLL)
- Korn shell has its own features & better than Bourne & c shell.
- Ksh program are easier to write & more concise & readable that c language.
- Has much better scripting language than any other popular language.
- Code is large.
- Ksh provide better performance.
- Korn shell language use the same syntax for built in command as for non built in
commands.
3) C shell :-
- C shell (csh) is a Unix shell developed by (Bill Joy for Berkeley s/w
distribution [BSD])
- Scripting syntax is modeled after the c programming language.
- Main use of c shell is as an interactive shell, but one can write program using c shell.
- It has customizable environment.
- A short hand can be assigned to command or sequence of command which is frequently
used.
- By assign an alias with alias command, one can essentially create their own command, i.e. it
has abbreviate command.
- It has job control.
- Programs can be urn in background or foreground.
- One can write program-using shell.
- C shell has Programming feature such as
1) checking of file permission
2) variable assignment
3) built in variable
Commands :-
1) Login commands
2) Logout
3) Password
4) Who
5) Who am I
6) Clear
4) Who am I :-
This command displays the information about the user who invoked the
command.
Syntax :- who am I
$ Who am I
Root Console Jan7 7.56 192.168.0.1
Options :-
1) - u :-
It add time slice last activity (also called as idle time) & PID of each
process logged in.
$ who – u
root console Feb 13 12.30 7354
2) – q :-
Quick option simply shows login id‟s & count the logged in users.
$ who – q
= users = 2
5) Clear :-
Clears the terminal.
This command clears the screen.
Syntax :- clear
Chapter : 5 UNIX FILE SYSTEM & RELATED COMMANDS
3 types of files
1) Ordinary files :-
- Also known as Regular file.
- Contains only data as stream of character.
2) Directory File :-
- Its commonly said that a directory contains files & other directories but it contains their
name & number associated with their name.
3) Device files :-
- Device & peripherals are represented by files.
- To read / write a device, you have to perform operation on its associated file.
Directory Files :-
- Directory file keeps details of files of subdirectories.
- Directory file contains entry for each file & subdirectory.
- Each line in a directory file contains only the name of item & numerical reference to the
location of item.
- The reference is called as i - number & index to the table is called i – list.
- i-list is a complete storage space available to file system.
Device Files :-
- Device file represent I/O devices, tty (terminal), a disk drive or a printer because Unix treat
such device as files.
- A degree of compatibility can be achieved between I/O (device) & ordinary I/O , allowing
for more efficient use of s/w.
- Device files can be either
o Character special file
o Block special file.
- Character special file can be deals with stream of character.
- Block special file deals with operates on larger block of data.
- Typical block size are 812 bytes, 1024 & 2048 bytes.
Links :-
- A link is ptr to another file.
(directory is list of name & i-number of file)
- There are 2 types of links,these are.
- Hard link i-number pts directory to another file.
- Soft link (symbolic link) provides an indirect ptr to file.
- Soft link is implemented as directory file entry containing a path name.
On Unix file system, every file & directory is owned by specific user.
- Permission assign to user can apply to specific file.
- File effective permission that have applied to specific user in relation to a file are
determined in logical precedence.
Basic Permission :-
There are 3 specific permission on Unix like system that apply to each class.
1) Read permission :-
Which grant the ability to read a file, when set for a directory, this permission grants the
ability to read the names of file in the directory.
2) Write permission :-
Which grant the ability to modify a file when set for directory, this permission grant the
ability to modify entries in directory.
This includes creating files, deleting & renaming files.
3) Execute permission :-
Which grant the ability to execute a file. This permission must be set for executable
binaries in order to allow the OS to run them.
When set for directory, this permission grants the ability to traverse its tree in order to
access files or subdir, but not see files inside the directory.
r - indicate read permission
w – indicates write permission
x – execute permission
Directory Permission :-
Directories also have its own permission & the significance of these permission differ a
great deal from those of ordinary files.
If default directory permission are not altered, the theory still appears.
Eg :- $ ls – ld programs.
Drwxr – xr – x 2 kumar metal 320 May9 9.57pm
The default permission of directory are rwxr – xr –x
Related Commands
1) ls :-
ls command is use to list the name of any file contained in current directory as well as
content of any subdirectories.
Syntax :- ls [option] [filename]
Useful Options :-
(1) ls – a
This option includes file beginning with a period in the list.
(2) ls – R
This option produce a recursive listing all files & subdirectories under the
current directory.
- r reverse
- s order by size
- t creation time
- u sort by access time
(3) ls – l
This option of ls include additional information (mode, number of link, owner,
group, size in bytes & time of last modification) for each file in list.
2) Cat :-
This command is use to concatenate & displays a file, i.e. it has 3 related functions with
regard to text file.
1) displaying
2) combining
3) creating new one
Syntax :- cat [option] [filename] [-] [filename]
[ ] – terms are optional
1) The most common use of cat command to read the content of file.
Syntax :- cat file 1
cat file 1 > file 2
the content of file 1 is written in file 2.
2) Concatenation :-
Concatenation is the 2nd role of cat is concatenation.
Eg :- cat f1 f2 f3.
This command will concatenate copies of content of 3 files f1, f2, f3
3) File creation :-
File creation is the 3rd use of cat is file creation for small files it is easier
than by using vi other editors.
Eg :- cat > file 1
3) cd :-
The cd (change directory) command change the current working directory to named
directory.
Syntax :- cd dirname
Options
1) cd temp dir
this is use to change directory to temp dir.
2) cd ..
move back one directory.
4) Rmdir :-
This command is use to remove /delete a directory from system.
Syntax :- rmdir directory name.
The directory must be empty while removing.
5) Mkdir
This command is use to create a directory.
Syntax :- mkdir directory name
12) grep :-
this command is use to find which file contain certain word.
Syntax :- grep <str> <files>
Eg – dict file contains
One way
Two ways
grep one dict
one way
13) head :-
this command is use to look the head of file
syntax :- head essay . 001
it displays the first 10 lines of files essay .001
To see a specific number of lines,
Eg – head – n 20 essay.001
This displays first 20 lines of file.
14) more :-
This command is use to read text files one page at a time.
Syntax :- more file name
Eg :- more poem
It let you read a file poem, one page at a time.
Options :-
q – quite more
spacebar – next page
return key – read next line
b – go back one page
15) tail :-
This command is use to look at the tail of file
Syntax :- tail f1
Eg – tail essay.001
Displays last 10 lines & for displaying last 20 lines
tail - n 20 essay.001
16) wc :-
This command is use to count number of characters, word & lines in files.
Suppose a file XYZ contains
One
Two
Three
Syntax :- wc XYZ
3 3 11
This shows XYZ file contains 3 lines, 3 words & 11 characters.
Options :
Wc – l XYZ (lines)
3
wc – w XYZ (words only)
3
wc – c XYZ (characters)
11
17) sort :-
This command is use to sort a file
Syntax :- sort file name
18) touch :-
This command let you change the date on file & also use to create a blank file.
Eg – touch f1
This will change the access date & time of f1 to current time
If f1 doesn‟t exist it will create a file (blank).
19) In :-
In creates link between files
- symbolic link are special files that contains the absolute or relative path to separate file.
- Reference to symbolic link are forwarded to file it points to
- The file to which the reference is forwarded is not aware of the link, if the file pointed to is
moved or deleted the link will just point to nothing.
- In Unix all information about file are stored in inode (file name). File name is stored in
directories where i-node number (OS refer to file) are paid with file name.
- The number of links entry in the inode keep tracks of how many times the inode number
has been paired with name in directory.
- Hard link –w when creating with In, the source file is only use to determine the inode
number.
- A new inode no-to-file name entry is then made in some directory using that inode number
& number of links counter is incremental.
- There is same file everyday i.e. file can be accessed by different names & / or different
location.
- Moving or deleting „original‟ source file has no effect on other links.
- Eg – to make soft link “hello”
“/home/alice/code/bin/world”
syntax:- In – s/home/alice/code/bin/world hello
20) Chown :-
Use to change owner & group of files. Normally root is allowed to do this but if user
owns a file, then that user can change the group, but only the groups containing that
user.
Options :-
-R
Recursively change / owner / group of entire directory tree.
-h
change owner of link, not target file
-f
indicates no error if change failed
eg – root changes the ownership of “/etc/password” & “/etc/shadow” to user root, group
wheel
chown root : wheel/etc/password/etc/shadow.
The same but changing the owner
chown root : /etc/{password, shadow}
The same but changing the group
chown : wheel/etc/{password, shadow}
21) man :-
man command is use to display help on syntax of Unix command.
Syntax :- man [option] [file]
Eg – man who
Obtain the information of who command.
Man – k password
To change umask, enter umask & three digit number that specifies your new umask
Eg – to change your umask to 027 enter following command.
$ umask 027
Unix determines the default modes by subtracting your umask from the octal number
777 i.e. if your umask is 027, your default directory mode is 750.
Chapter : 6 TEXT EDITING WITH Vi EDITOR
Introduction to vi editor
The vi is most commonly used text editing tool in Unix
- You can see part of file in a window on the screen & editing operation can be controlled by
moving cursor around the text on screen.
- Once you learn vi, you will find that it is fast & powerful editor.
- vi has no menus, but instead you use combination of key strokes in order to accomplish
commands.
- Last line is used for special information.
- The lines are mark with (v) tilde.
Modes in Vi
Each mode has its own characteristic / operation. There are 3 different modes
1) command mode
2) insert mode
3) last line mode (command line mode)
1) Command modes :-
After a file is opened it is opened in command mode, that is s/p from
keyboard will be treated as vi commands & you will not see the word
you are typing on screen.
2) Insert modes :-
To enter the text you have to print / put vi in insert by pressing “i” or “a”
after that you can type / add text on screen.
To switch between modes Esc key is used
Esc (i) – text mode
Esc (command mode)
3) Last line :-
Entered by :,/,? Or !
Input is read by echoed at the bottom of the screen.
- command executed by <RETURN> or <ESC> terminated by ^C
Existing in Vi
1) Quit without saving :
If you don‟t want to save the work : q will take you out without saving your
editing in vi.
3) Forced quit :
An ! sign at the end of exit command (:q!, :wq!) causes a forced quit form vi
after ignoring / writing all changes.
Vi COMMANDS
Left h
Right i
Up k
Down j
Line
Beginning ^ or B
End $
Sentence
Next sentence )
Previous sentence (
Paragraph
Next }
Previous {
File
Go to end of file :$
One character forward :w
One word forward :W
Go to line number :line_number
Displaying file information ^g
Inserting & appending
Insert text to left of cursor i
Insert in beginning of line I
Append to right a
Append to end of line A
Adding a new line
Adding a new line below
current line o
Add above current line O
Deleting the text
Delete text above the text x
Delete text character on right of
cursor X
th
Delete 20 line 20d
Delete current line dd
Delete till end of current line D
Replacing a character & word
Replace character above cursor r
Replace character until
ESC is pressed R
Replace the word from cursor
to end indicated by $ sign cw
Replace till end of line c
Substitute
Substitute current character s
Substitute entire line S
Undo the last change
Undo last change u
Undo last to current line U
Copy & pasting lines
Copy the current line
into buffer YY
Copy 5 lines from
current line 5YY
Paste the current buff. P
Searching
Searches for word name
in file :/name
n continue search forward n
N search back word N
Saving
Save but don‟t quit :w
Save & quit the editor :wq
Save zz
Quit without saving q!
Search & replace s / <search – string> / <replace>
Repeating last command .
Recovering an unsaved vi file vi – r filename
Chapter : 7 I / O REDIRECTION & PIPING
Concept of Redirection :-
Redirection is the switching of standard stream of data so that it come from a source other than
its default source or so that it goes to some source or so that it goes to some destination other than
default destination.
OR
In Unix, to send O/P from a process to different device or another process via a pipe or process
read its I/P from different file, device or pipe.
According to 1st Definition, in Unix OS each command & process, is automatically assigned 3
data streams
1) one I/P stream called as standard i/p
2) two data stream called as standard o/p & standard error.
All consist of plaint text (human readable alphanumeric character) & are considered as type of
text file, & all are associated with console (keyword & text mode display screen by default.
Console instrument panel containing
Terminal equipment including a display monitor & keyboard connected to computer
- Command specifies program to run
- Process is instance of program in execution.
- Standard input is the source of input for command (text type in keyboard by default) but it
can be redirected to come from some other source such as file or another program.
- Standard output & standard error are the destination of output & error messages from
command (display monitor by default) but they can be redirected to go to other destination
(file, printer or another program)
- By using the standard stream makes the redirection in simple manner & it is the major
factor in flexibility & convenient of Unix like OS.
because by using standard stream has advantage that process do not need to be aware
the redirection occurring & simplifies the program development.
- Redirection device can be classified into 2 categories :
1) argument
2) redirection operators
- argument is the name of file or other data that is provided to command in order for
command to use it as input & it redirects standard I/P from being the keyboard to being that
file or data.
Example:-
If the head command, (read the 1st 10 lines of text, it is used without any
argument
head
It will read the 1st 10 lines of text type 10 at keyboard i.e. standard I/P, & repeat those
lines to standard o/p (display)
- This can be seen by pressing Enter () which moves on next line for typing the desired text.
After entering some text, pressing enter key again move to another new line allowing
command to be executed by simultaneously pressing ctrl + d key.
- This means the text was typed at keyboard to be read from standard I/P & then be written
to next line of display screen.
- When a file named,
Eg
File 1 is used as argument with head, standard I/P is redirected from being a
keyboard to being that file i.e.
Head file 1
- Standard I/P could just as easily redirected with multiple argument, so that I/P data comes
from multiple file.
Eg – head file 1 file 2 file 3
- In this case, the head will by default read the 1st 10 lines from each file & write them to
display screen.
Redirection Operators
- Redirection operators can be used to switch both the source & destination of standard
stream of data in commands.
- They can be classified as
1) I/P
2) O/P
3) Error
4) Pipe
- Can be formed mainly from 3 characters
1) leftward pointing angle bracket (<)
2) rightward pointing angle bracket (>)
3) vertical bar (|)
- To redirect standard I/P, so that command obtains its I/P from a file instead of keyboard, the
I/P redirection operator, which is represented by leftward point angular bracket, can be used
(<).
Eg – the standard I/P for head can be redirected to file named file 4 with the following
head < file 4
& same by using argument i.e.
head file 4
- Standard o/p & standard error both are by default the display screen. (when a command is
issued in absence of any redirection the two o/p stream will be displayed on screen)
- The o/p redirection operator (>) can be used to redirect standard o/p.
Eg – the o/p of cat command can be used to read files, it could be redirected when reading a
file 5 from displayed screen to file name files 6, with following :
Piping
Standard input and standard output constitute two separate streamsthat can be individually
manipulated by shell.
We kmow that who command is use to produce a list of users,one use per line. if you save this
output in file and apply the wc-l command to count the number of lines in this file, then you
would have effectively counted the number of users.
This method have certain disadvantages:
You require an intermediate file that has to be removed after the wc command
has completed its run.
The process is slow
Difficult to handle complex task.
When handling large files,it can occupy space of the disk.
The shell enables the standard output of one command to be connected as standard input to
another. A special operator is used to do this – the | (pipe),which acts as a connector of two
commands. A pipeline is use to count the number of differences between two files.
In a pipeline, all programs run simultaneously.
The feature of pipelining represent one of the most important aspect oif unix system.
A common use for pipes is to control the output of large files to the screen.
Unix allows you to connect processes by considering the standard o/p of one process feeds
into I/P of another process this mechanism is called as pipes
Connecting simple processes in a pipeline allows you to perform complex taxk without writing
complex program.
o Eg – how could you use head & tail in pipeline to display lines 25 through 75 of file?
cat file | head 75 | tail 50
The cat command feeds the file into pipeline. Head command gets the 1st 75 lines of file &
passes them down the pipeline to tail.
Useful options :-
1) grep – i pattern file
print all lines of file that contains the pattern, regardless of case.
Eg – grep – i cg data
Print any line of data that contations “cg” “Cg” “cG” or “CG”
The –i option ignores the case of string when searching
2) grep –v pattern file
prints all lines of file except those that contains patterns.
b) Fgrep
Fgrep searches file for one or more pattern argument
It does not use regular expressions instead it does direct string
comparision to find matching line of i/p
c) Egrep
Works in similar way, but use extended regular explanation
matching patterns
Eg – egrep p{2}*
OR
Cut command selects the list of column or fields from one or more files.
Options –c is for column
-f is for field
it is entered as
2) paste
paste command merge the lines of one or more files into vertical column
separated by tabs
if for eg – the files contains
this is first line
& file 2 contains
this is file 2
then by executing / running this command
Options
-d „char‟ separates column with char instead of a tab
-s merge subsequent file lines form one file.
3) Join :-
Join command is use to join lines of 2 files in common field
Options : - - a print a line for each unpairable line in file.
-e replace empty o/p field
Zzz
Aaa
1234
yuer
wer
qww
wwe
then after executing sort file 1
o/p
1234
aaa
qww
wer
wwe
yuer
zzz
Options :-
-b ignores leading space & tabs
-c checks whether file are already sorted
-d ignores punctuation
-i ignores non printing characters
-n sort in arithmetic order
-o file put o/p in file
+m[-m] skip n fields before sorting & sort up to field position m.
-r reverse the order of sort
-u identical line in o/p file appear only one time in o/p
2) Uniq :-
This command removes duplicate adjacent lines from sorted file while
sending one copy of each second file.
Syntax :- sortnames | uniq – d
This will show which line appear more than once in names file
Options :-
-c prints each lien once, counting instance of each
-d prints duplicate line once, but no unique lines
-u prints only unique lines
4) Comparing files :-
1) Cmp :-
This command compares 2 files
Eg- suppose there are two files
File one file two
Then cmp file one file two will give
File one file two differ : char 80, line 4
If this command run on one file nothing will return as o/p
2) Diff:-
Compare the 2 file & print out the difference between 2 files.
Eg – there are 2 files
File 1 File 2
sss sss
then then
123 123
two 456
3c3
O/p – 123
456
3) (cu) :-
this command is used for communication over a modem or direct line
with another Unix system.
Syntax :- cu option destination
Option :-
-bn process line using n bit char (7 to 8)
-d print diagnostics
-e sends even parity data to remote system
-n prompts the telephone number
Destination :-
Telno is telephone number of modem which we connect
to
System call the system known to UUCP
Aadr is an address specific to LAN
The cal command can be used without argument, in this case it displays
the calendar of current month
$ cal
2) Date :-
Displaying the system date
The Unix system maintains an internal clock meant to run perfectly
When system is shut down, a battery backup keeps the clock ticking.
You can display the current date with date command which shows date
& time to the nearest second.
Syntax :- $ date
Wed Aug 31 16:22:40 IST 2005
This command can be used with suitable format specified as argument.
Each format is preceded by + symbol, followed by % operator & single
character described formed
For eg- you can print only the month using the format +%m
$ date +%m
08
OR month name
$ date +%m
aug
OR you can combine them in one command
$ date + “%h %m”
Aug 08
Options :-
- d deleting characters
- s compressing multiple consecutive characters
- c complementing values of expression
8) Tools for mathematical calculation
1) bc :- (the calculator)
Unix provides 2 types of calculator
1) a graphical object (X clac cmd)
2) text base bc command
When you use bc command without argument the cursor keeps on
blinking & nothing seem to happen.
$ bc
12 +5
17
(ctrl – d)
bc shows the o/p of computation in next line
Start bc again & then make multiple calculation in same line, using (;) as
delimiters.
- the prompt returns & all your keystrokes (including the one used to backspace) that you
now entered here get recorded in file typescript
- after your recording is over, you can terminate the session by entering exit
$ exit (or use ctrl + d)
script done, file is typescript
$_ (back to login shell)
Communication :-
1) telnet (remote login)
The telnet command, belonging to DARPA command set, allows you to log on a
remote machine.
If you have account on a host in local network (or on internet) you can use telnet
with hostname or lPadd as argument
$ telnet 192.168.35.12
trying 192.168.35.12
connected to 192.168.35.12
escape character is „^]‟
sunos 5.8
login :-
Using telnet protocol one can communicate with another host
You can close a telnet session in 2 ways
1st you can use the shell‟s exit command, or you can escape to the telnet
prompt <ctrl - ]> close the session, & quit to exit to the local shell.
3) Write : -
By using this command you have 2 way communication with any person who is
currently logged in
- one user write a message & then waits for reply from other
- communication continue till both user decide to terminate conversation
- write uses login name of remote machine as arguments & text message form standard I/p
- Syntax :- $ write abc [message]
4) Mail :-
Mail is one of the well known command in Unix. It response is system
dependent but generally is prompts for subject to be enter before the main
message
$ mail abc
- mail is post marked with name of sender, as well as date & time of sending it
- there are number of internal commands that you enter at the & prompt
- you can save, delete, reply to or simply ignores the mail that you have received
- if you don‟t remember the different command you have to simply enter a ? for help.
- Mail saves message in mailbox which is normally placed in directory / var / spool/ mail &
has some name as login name.
- Once mail respond with an & you can see the next message
- Enter + at the prompt to see further mail & - to display immediate preceding
message
Commands Action
+ print next message
- print previous message
N print message numbered N
h print header of all message
dN delete N message
uN undelete N message
sflame save current message with header & post mark in
flame
wflame save without hearder
muser forward mail to user
vN replies to sender of message N & delete after reply
q Quit mail program
!cmd run Unix command
5) News :-
The news command is use to read the message which is send by system
administrator
Syntax - $ news
News is meant to display all files that have been created in / usr / new since lat
time the command is executed.
When there are number of unread messages, news, by default, display them in
sequence, the most recent item shown 1st.
Options :-
-n displays only the file name of those messages that have not been
displayed
-s list the number of news items that have still not been read.
6) Finger :-
Has communicating features when used without argument it simply
produce a list of all logged user.
Unlike who finger can also provide details of single user
Syntax :- $ finger
Options –
-f full listing
i.e. to get the detailed listing which also shows the parent
of every process use - f (full) option
-u - displaying processes of user i.e. to know the activities of any user
-a - displaying all user process i.e. to know the activities of all users but
doesn‟t display the system processes.
2) Nice :-
Ni process in unix system are executed with equal priority. This is not always
advantageous because if any job has highest priority cannot be executed earlier.
So Nice command is used with & operator to reduce the priority of job
More important job can then have greater access to system resources
To run the job with low priority, the command name should be prefixed with
nice
Nice wc –1 uxmanual
OR
Nice wc – 1 uxmanual &
Nice value are system dependent & typically range from 1 to 19.
Command execute with nice value that is generally in middle of range usually
10.
Higher nice value implies a lower priority
Nice reduces the priority of any process by ranging the nice value.
You can specify the nice value explicity with –n option
Nice –n 5 wc –1 uxmanual &
3) Kill :-
Kill command is use to terminate process & can use one or more PID as its
argument by default uses the SIGTERM (15) signal thus.
Syntax :- kill 105
Terminate the job havingPID 105
If you don‟t remember the PID use PS to know that & then use kill
If all these process have same parent you may simply kill the parent in order to
kill all its children.
4) At :-
Unix provide a efficient facilities to schedule a job to be run at specified time of
day rather than now
The at & batch command make such scheduling possible
At take time of jot as a argument of execution, I/P come from standard I/P
Syntax :- $ at 12:10
At > empawk2 .sh
Ctrl d
Command will be executed using /user/bin/bash
It also takes key words now, noon, midnight, today & tomorrow which is used in
this command
Eg – at 15
At 5pm
At noon
At 9 am tomorrow
At now + 1 year
The job can be listed with the at – l & removed with at – r.
5) Batch :-
The batch command also schedule job for later execution, but unlike at,
job for later execution, but unlike at, job are executed as soon as system load
permits.
The command doesn‟t take any argument but uses an internal algorithm
to determine execution time.
Response of batch is similar to at
Syntax - $ batch < empawk2. sh
Command will be executed using / usr / bin /bash
Any job scheduled with batch goes to a special at queue from where if
can be removed with at – r
6) Cron :-
Cron command is use to execute program at regular intervals, i.e. every
minute it wakes up & look in control file.
Cron uses an unusual matching system for matching field. It set of
number is to delimited by comma.
7) Crontax :-
You can create your own crontab files with vi in the format
It uses standard I/p & when used without argument the I/p has come
from keyboard.
$ crontax cron.txt
you use crontax command to place the file in the directory containing
crontax file for cron to read the file again.
Eg – if XYZ run this command, a file named XYZ will be created in
/var/spool/cron/crontab containing the contents of cron.txt.
A cron tab file with –r option is removed when the system clock is reset,
cron is aborted & restarted cron should never be kill, not even by system
administrator.
Like at & batch the use of cron is controlled by some sytem file which
can be edited by SA.
8) Sleep :-
You may need to introduce some delay in shell script to set the user see
some message on screen before the script start doing something else.
Sleep is the command which delay in shell script. Argument use with this
command is number of seconds for which the shell will pause or sleep
before it resumes execution.
Syntax :-
$ sleep 100 10 seconds have elapsed
The message appears exactly 10 second after the command have been
invoked.
9) Wait :-
The parent then executes the wait system call to wait for the child
process to complete.
It picks up the exit status of child & then continues with its other
functions.
1) Mount command :-
This command is important for handling file system, & has its own
configuration files which it reads when invoked.
Mounting is achieved with the mount command which normally takes 2
argument the system of file system & the directory under which it is to be
mounted.
Syntax :- $ mount / dev / abc
Shell keywords :-
Keywords are the word whose meaning has already been defined to the shell.
- The keyword cannot be used a variable name because if we do so, we are trying to assign a
new meaning to the keyword which is not allowed by the shell.
Shell Variable :-
These are standard variable which are accessible shell provides value of these variables.
- These variables are used by system itself & control the environment.
- We can change the value of these variable as per our preference & customize the system
environment.
- The $ prompt that we see is default value of unix defined variable PS1 stands for system
prompt 1.
- We can assign different value to PS1 if we want the prompt to be something other than the
$.
$ PS1 = “HI”
So now everytime the system prompt you it displays not the $ but HI.
Variable Meaning
MAIL CHECK Define the duration after which the shell checks
weather the user has received any mail .
By default value is 600
IFS Define the internal field separates, which is space
a tab, or new line.
The read command enables parameter value to be entered interactively by the user while the
script is running.
It is usual to provide a priompt for the user as in the script losted below (called greeting).
Echo “whats your name?”
Read name Echo “Hello, $ Name”
This can give the following results.
% greetings - execute the script what‟s your name?
Output Jenny _ the shell waits for your I/P
Hello, Jenny _ O/P %
The read statement in the shell‟s internal tool for taking I/p from user is making script
interactive. It is used to shell with one or more variables.
Input supplied through the std I/p is read into these variables.
When you use statement like
Read name
the script pauses at that pt to take I/p from keyboard.
More than one parameter can be given to read command, usually separated by one or more spaces as in
the following script (called count).
Echo How for can you count?
Read first second third
Echo first & second third
This can run to give full %count.
How far can you count?
123 - uses I/P 123 –script O/p
DECISION STASTEMENT
1) If then fp.
The if statement makes 2 way decision depending on fulfillment of certain condition, In
shell the statement use the following forms.
1. If command is successful
Then
Execute command
Else
Execute command
fi
2. if command is successful
then
execute command
fi
3. If command is successful
then
Execute commands
elif command is successful then
else
fi
- If also requires a then it evaluate the success or failure of command that is specified in its
“command Line”
$emp3. sh mail
pattern not found.
#!/bin/sh
#emp3. sh:Using if & else.
#if grep “^$1”/etc /password 2>/dev/null
(search U name at beg of the line.)
then
Echo “pattern found –job over”
Else
Echo “pattern not found “
fi
Test: (when you use to evaluate expression, you need the test statement because the true or false
values returned by explanation can‟t directly handle by if test uses certain operator to evaluate the
condition its eight &returns either a true or false exit status which is then used by if for making
decision.
test work in 3 ways
1> compare 2 no
2> cmp 3 string
3> check a file attribute.
Numerical comparison operator used by test
Operator Meaning
-eg equal to
-ne Not equal to
-gt greater than
-ge greater than or equal to
-if less than
-ie less than or equal to
- Test command can be used in its simplest form to test if a string exist as following script
% cat test 1 %test
echo “Type something please” Type something please
read a Hello
if test $a Thank you
then echo “thank you” %test 1
else echo “thanks for nothing” Type something please
fi Thanks for nothing
%
Case conditional
The case statement is second conditional offered by shell.
The statement matches an explanation for more than one alternative & uses a compact construct
to permit multi way branching
- Case also handles string tests but in a more efficient manner than if
The general syntax stmt is follows
Case expression in
Pattern 1) commands 1;;
Pattern 2) command;;
Pattern 3) commmand 3;;
esac
1 eg
#!/bin/sh
#menu .sh:uses case to offer 5 item menu
#
echo “menu in
1.list of files/n
2.process of uses/n
3.todays date
4. uses of system/n
5.quit to unix/n
Enter your option:/c”
read choice
case “$choice” in
1)is -/;
2)ps-f;
3)date;
4)who ;
5) exit;
*echo “invalid option”
esac
Case 1st matches expressions with pattern 1
If the match succeeds than if executes command 1 which may be one or more commands
-If the match fails then pattern 2 match & so forth
Each command list is terminated with pair of semicolon &the entire constuioct is close with
esac (reverse of case).
Eg. Consider a simple script /menu sh.
That uses case .The script accept the value from 1 to 5 & perform action depend on number 5 Menu
choice are displayed with multilane echo stmt.
- Case matches the value of $choice with the string 1,2,3,4,5, If user enter! 11s-1
command is executed from eg 11 option 5 quit the pgm. The last option (*) matches any option not
matches by previous option.
Looping stmt:-
1) for loop:-
the shells for loop differ in structure from the ones used in other programming language.
These is no three part structure or used in c, awk, perl.
Unlike white & until, for loop doesn‟t test he condition but instead of it uses list
Syntax:-
For variable in list
Do
Commands
Done
- the loop body also uses the keyboards do &done but additional parameter are variable
& list.
- Each white space separated word in list &that list is assigned to variable & command
are executed until list is exhausted.
Eg:-
$ for file in chap20 chap 21 chap22 chap23 ; do
>cp$file ${fike}.bak
>echo $file copied to file bak.
>done.
Chap 20 copied to chap 20 bak.
Chap 21copied to chap 21 bak.
Chap 22 copied to chap 22 bak.
Chap 23 copied to chap 23 bak.
-The list here comprises a series of character string (chap20 onwards) representing filenames
separated by whitespace.
-Each item in the list is assigned to variabe file. File 1st get the value chap20 ,then chap21 &so
on
-Each file is copied with a bak extension & cp,pleth message displayed after every file is
copied.
While looping
-The command enclosed by do & done are executed repeatedly till condition remains true.
Eg:- the script emp5.sh accept a code &description in same line & then writes the line to new list. It
then prompts you for more entries .The loop
It cet is controlled by value of $answer.
Eg:-#!/bin/sh.
#emp5.dh. dhow use of white loop
#
answer =(#must set to y for entering
while {“$answer”= “y”} the control command
do
echo “enter the code &descript :”>dev /tty.
Read code description #read both together.
Echo “$code/$description” >>new list .
(Append a line to new list)
echo “enter any moer (Y/N)?c”>dev/ttty
read any more
case $any more in
Y*/y*)answer=y;:
N*/n*)answer =N;:
*)answer = y; (any other reply means y)
esac
done
$emp5 :sh
enter code &descriptn :03 analgesice .
enter any more (y/n)?
enter code and description:04 analgesics.
Enter any more (y/n) ? (enter)
Enter the code and description 5 otc drgs
Enter any more (y/N)?
5) until :while complement
The until statement complement the while in sence of loop body that is executed repeatedly till
condition remains false
The general syntax of until loop is
Until [-r abc 1st] #until the file abc 1st can be read.
Eg:
Flag =y
Until test $flag = N
Do
Echo do it again?
Read flag
Done
you can use the & & &!! operator in same form way you used them with awk ,bsh &p
Positional parameter:-
Some unix command like date produce single line O/p we also pass command o/p through file
like grep &head to produce a single line we have to use external command (cut) to extract a field from
date o/p.
Case date!cut –D” “fi”in this ois overcome , the shell has internal cmd to do this job (set) set
assigns its argument positional parameter $1,$2,&so on this feature is especially use full for picking up
individual field from o/p of pgm.