Unix Notes
Unix Notes
Unix - Notes
Definition of UNIX
UNIX is a portable, multitasking, multiuser, time sharing operating system(OS).
Founder of UNIX
The UNIX was founded by Ken Thompson, Dennis Ritchie and Brain
kerninghan at AT& T Bell Labs research in 1969.
Founder of LINUX
Linus Benedict Torvalds in 1991.
Need of UNIX
Network capability:
With other OS, additional software must be purchased for networking but with
UNIX, network capability is the part of the operating system.
History of UNIX
1960 Bell labs involved in the project with MIT, General Electric and Bell
Laboratories to develop a time sharing system called
MULTICS(Multiplexed Operating and Computing System).
1969 Ken Thompson wrote the first version of the UNIX called
UNICS(Uniplexed Information and Computing System)
1970 Finally UNICS became UNIX.
download) one)
UNIX has very high security system Windows has low security system
UNIX is a command based operating Windows is not a command based
system operating system
The file system is arranged in The file system is arranged in parallel
hierarchical manner manner
UNIX is not a user friendly Windows is a user friendly
Free office(such as excel, PowerPoint Pay for MS Office
and others)
Low Hardware cost High Hardware cost
Customizable add features Not customizable
The Architecture of the UNIX system is divided into 4 major components. They are:
1) The Kernel
2) The Shell
3) Files and Processes
4) System Calls
1. The Kernel
The Kernel is the heart of the Operating System.
It interface between Shell and Hardware.
It performs Low Level Task.
Eg: Device Management, Memory Management etc.
2. The Shell
Features of UNIX
1) Simple design, organization and functioning
The architecture of the UNIX is simple, organized and functional.
2) Portability
The code can be changed and compiled on a new machine.
3) UNIX Shell
The user interface UNIX Shell provides the services that the user wants.
4) Hierarchical file system
UNIX uses a hierarchical file structure to store information.
5) Multi user
UNIX allows more than one user to share the same computer system at the
same time.
6) Multi-tasking
More than one program can be run at a time.
7) Security
UNIX provides high security level( System level security and File level
security)
8) Pipes and Filters
In UNIX, we can create complex programs from simple programs.
9) Utilities
UNIX has over 200 utility programs for various functions.
10) Machine Independence
The system hides the machine architecture from the user, making it easier to
write applications that can run any computer system.
Architecture of Kernel
The system call and library interface represent the border between user
programs and the kernel.
The File subsystem manages files, allocating file space, administrating
free space, controlling access to files and retrieving data for users.
Kernel Interface to Hardware is responsible for handling interrupts and
for communicating with the machine.
Device drivers are the kernel modules that control the operation of
peripheral devices.
Block I/O devices are random access storage devices to reset the system.
Scheduler module allocates CPU to processes.
Memory management module controls allocation of memory.
Inter-process communication (IPC) ranges from asynchronous signaling
of events to synchronous transmission of messages between processes.
Features of Kernel
1) Concurrency
Many processes run concurrently to improve the performance of the system.
2) Virtual Memory(VM)
[Type here]
CHAPTER-2
Introduction
A file is one in which data can be stored.It is a sequence of bits,bytes or lines and stored on a
storage device like a disk.Inunix everything is stored in terms of files.It could be a program,an
executable code,a file,a set of instructions,a database,a directory or a subdirectory. A unix file is a
tool or an application that defines the structure of the file and its format.
Unix Filenames
Unix is case sensitive! So a file named my data. Txt is different from mydata.txt
which is again different from mydata.txt.
Unix filenames contain only letters,numbers and the_(underscore)&.(dot)
characters.All other characters should be avoided. The /(slash) characters is
especially important/since it is used to designate subdirectories.
It is also possible to have additional dots in the filename.
The part of the name that follows the dot is often used to designate the type of file.
Files that end in.TXT are text files.
Files thatend in.C are source code in the ‘C’ language.
Files that end in.HTML files for the web.
But this is just a convention and not a rule enforced by the operating system.this
is a good and sensible convention which you should follow.
Most UNIX system allow a maximum of 14 characters as the length of a
filename. However it depends on the UNIX variant used.
FILE SYSTEM
pg. 1
[Type here]
2. List of storage blocks: The storage space is divided up into a series of standard
size blocks.
3. Number of free blocks on the file system.
4. A list of free blocks with their location.
5. Index to next free block on the list.
6. A list of free inodes.
3) The Inode Block
Information about each file in the file system is a special kernel structure called an
inode.
It contains a pointer to the disk blocks containing the data in the file,information
such as type of file,permission bits,the owner and group,file size,file modification
and so on.
The name of each file is listed in the directory the file is associated with.A directory
is special type of containing a list of filenames and associated inodes.
When a user attempts to access a given file by name,the name is looked up in the
directory. Where the corresponding inode is found.
An inode for a file contains the following information
File owerid : It is the numeric id used in the password file to
uniquely identify a user on the system.
Group id (GID) :This identifies a group that can be granted special
access by the ower.
File type :It indicates whether inode represents a
file,adirectory,aFIFO,character device.
Types of Access
4) Data Block
It contain the actual data contained in the files.
These blocks follows the inode table and occupy most of the storage device
space.
It allotted to one file cannot be allotted to another file, unless the two files
are linked.
Advantages
Data in small files can be accessed directly from the inode.
Once read operation fectures the inode ,and another read fectures the first data block.
Larger files can be accessed efficiently .
Disk can be filled completely ,with little with wasted space.
Disadvantages
pg. 2
[Type here]
Since inode information is kept separetly from data access of data often requires a long
seek when files is initially accessed.
Orginal file system uses only 512 bytes blocks, an insufficient transfer size.
Free list quickly becomes scrambled increasing overhead of finding free blocks.
Types of Files
The unixos is built around the concept of the a file system which is which is used to store
all of information. Including the operating sysem kernel itself.
There are 4 types of files:
1. Ordinary or Regular files
2. Directory files
3. Device files or special files
4. Hidden files
1. Regular or ordinary files: It can contain text, data,or program information, files
cannot contain other files or directories. Instead use the underscore(’_’) symbol.it is
ordinary file.
An ordinary file can be of 2 types.
i. Text file
ii. Binary file
I. Text File: A text file contains only printable characters.it contains line
of character, each line terminated by a newline character .
Ex:text files include c and Java program ,shell and perl scripts.
II. Binary File:a binary file contains both printable and unprintable
character(0 to 255 ASCII code).
Ex:binary files include unix command ,object code of c programs
,pictures,sound,and video files.
pg. 3
[Type here]
Types of users
1. The ower of file(user)
2. The users who belong to the same group as the file(group)
3. Everyone else(other)
Directories are organised into a hierarchical structure that fan out like an upside own tree.
The top most directory is known as root and it is written as (/).
The roots contains subdirectory and each of these can contains more subdirectory and so
on.
Directory Contents
/ The root directory
/bin Essential low-level system utilities
/usr/bin Higher-level system utilities and application programs
/sbin Super user system utilities (for performing system
administration tasks )
/lib Progarm liberaries (collections of system calls that can be
included in programs by a compiler)for low level system
utilities.
/usr/lib Program libraries for higher level user programs
/tmp Temporary file storage space (can be used by any user)
/home User home directories containing personal file space for
each user.each directory is named after the login of the
user.
/etc Unix system configuration and information files.
/dev Holds the files /device drivers necessary to operate peri-
pherals such as terminals , keyboard,printer,hard disk etc
/var Contains files that vary in size,mail
directories,printer,spool file,logs etc..
/usr/include Contains standard headed files used by c programs
pg. 4
[Type here]
It is the owner of the file.the owner’s permissions determine what actions the owner of the File
can perform on the file.
Group:
It gives the name of the group.the groups permissions determine what actions a user,who is
a member ofthe group that a file belongs to , can perform on the file.
Other:
the rest of the world who are not the owner . the permissions for others indicate what
action
Ls options :
-a : list all files including hidden files . Hidden file names start with a dot character.
A single dot (.) refers to the current directory and a double dot (..) refer to the parent
Dirctory .
i. Creating files :
cat command can be used to create small files
syntax :
pg. 5
[Type here]
Example :
Apple
Banana
Orange
syntax :
$cat filename
Ex :
Carrot
Beans
Tomato
Apple
Banana
orange
carrot
Beans
Tomato
Cat command can concatenate the contents of two or more files and start
Syntax :
Ex :
pg. 6
[Type here]
$cat food
Apple
Banana
Orange
Carrot
Beans
Tomato
Syntax :
$cat >> filname1
Ex :
$cat fruit1
Grapes
(ctrl + d)
Options
Cal command :
Cal command is used to print the calender of a required month or year
Syntax :
Ex :
syntax :
date options arguments
pg. 7
[Type here]
options :
Ex :
$date
Sat jan 05 15:35:30 1st 2016
Who :
Who command provides the login details of all current users in 3 columns format.
Syntax :
Who options ami
First column shows login names , second column shows the devices names of the
terminals and third column shows the login date and time .
Options :
syntax :
printf format arguments
Syntax :
Tty
Ex :
pg. 8
[Type here]
$tty
/dev/pts /1
Sttycomman:
Set teletype. It will change and print the terminal line settings.
Syntax:
Stty[-a/g] [-f device] [settings]
Options:
-a :print, all current setting in human readable form.
-g(save): print all current setting in a stty readable form.
-f:(file): open and use the specified device.
Syntax :
Uname options
Options
Passwd :
It is used to change password in passwd .
Syntax :
$passwd
echo :
it is usually used in shell scripts to display messages on the terminal
syntax :
echo options arguments
Ex :
pg. 9
[Type here]
I am studing in 2 Bca
syntax :
tput options row_num column _num
Bc : calculator command
there are two types of calculator .
Syntax :
bc arguments
Ex :
$bc $bc $bc
15+5 sqrt(49)10/3
20 7 3
21 22 23
script command:
it is a unix utility that records a terminal session. after executing yhe script
command it starts recording everything printed on screen including I/p and O/P until
exit.by default , all the terminal information is saved in the file typescript, if no
argument is given.
Ex:$script
script started, file is typescript
Spell command :
Read one or more files and print a list of words that may be misspelled .
Simplest a sometimes most convenient of these spelling chekes the spell.
Spell compares words typed in the keyboard or the contents of a text file to those in a
built in a directory files and there written all of the words not in the directory to a
standard output ( which displace screen by default )
Syntax :
pg. 10
[Type here]
ispellcommand :
If the directory contains any near missletters (that is words that differ by only a single
character , a missing or extra letter , missing space or _
ispellfilename :
r : replace the misspelled word completely .
a : accept the word for the rest of these ispell session .
I : accept the word capitalized as it is in the file and update the provide directory .
U :accept the word and add a lowercase session to the provide directory .
Syntax :
Pwd
Ex :
$pwd
/home/rama
Pathnames :
It is the notation used to point to the particular file or directory
a) Absolute path :
Absolute path all ways starts from root directory (/) .
pg. 11
[Type here]
Ex :
User /jen /person
b) Relative path :
It points to a file or directory relative to your current working directory .
Ex :
Person /art.html
Syntax
Cd pathname
Ex :$pwd
/home/rama
$mkdirpartha
$cd partha
$pwd
/home/rama/partha
mkdir:making directors
mkdir command is used to creat new directories.
Syntax:
mkdir optionsdir-names
ex:$mkdirranjitha
$cd ranjitha
Ranjitha$ pwd
/home/ranjitha
rmdir:
It removes one or more directories or subdirectories.
Syntax
rmdirdir-names
ex: $cd\
$rmdirranjitha
pg. 12
Standard files are the special files which are the streams of characters seen as input
or output by the commands. There are three files representing three streams, each
associated with a default device.
Standard input(stdin)
Standard output(stdout)
Standard error(stderr)
Standard input: is a file or a stream representing input. Keyboard is the Standard input
file .But we can use redirection with the < symbol or pipeline with the symbol | to specify
other files as input files.
Standard error: it is a file or stream representing error messages that emerge from the
command or the shell. This is also connected to display screen.
Each standard files are represented by a number called file descriptor, they are
0standard input
Key Board
1standard output
2standard error
Display
unit/Monitor
I/O Redirection: Redirection is a feature that reassigns the standard input and output
files. For input redirection (input source) < operator is used, so that input is not from
keyboard, but from another file. And for output redirection > or>> operators are used,
which outputs to other files but not to the terminal.
Eg: $ banner < file1 [ it takes input from file1 and displays it on monitor]
Piping : it is a feature available in Unix where two or more commands can be combined
together. Here output of first command is treated as input for second command. The
symbol used for pipe is | . A sequence of commands using one or more pipes is called a
pipeline. The advantage of pipe is that, a command line containing many commands can
be executed as a background process.
[ here output of the command cat is directly send as input to sort command]
Filters: Filters are UNIX commands that take their inputs from the standard input file,
process it and send it to the standard output file. A filter is actually a program that can
read directly from files whose names are provided as arguments, process it or filer it and
sends the result to the standard output, unless a redirection or a pipeline symbol is used.
Some commonly used filter commands are :
cat
head
tail
cut
paste
uniq
tr
wc
sort
grep
NOTE: All filter commands does not change the contents of files but changes will appear
only while displaying. The changes can be stored permanently by using redirection
facility
cat: This command is a multipurpose filter command used for creating file, displaying
contents of file, copy file, append to file and to concatenate two or more files.This
command is already discussed in earlier chapter.
Options
-n : displays each line with its line number
-b : same as -n but it ignores blank lines
-u : the output is not blubbered
-s : silent about nonexistent files
head: This command is used to display the first few lines of a file. The user can specify
the number of lines to be displayed by using the n argument. The default number of lines
Page2
Selected options:
-cn : print the first n characters of the file
-n : print the first n lines the default is 10
$ head dolls [ displays first 10 lines of dolls file ]
$ head -5 dolls [displays first 5 lines from dolls file ]
$ head -c5 dolls [displays first 5 characters (including white space) from dolls file ]
tail: This command is used to display the last few lines from a file. The user can specify
the number of lines to be displayed by using the n argument. The default number of lines
that are displayed is 10.
Syntax: tail [-options] filename
Selected options:
-cn : print the last n characters of the file
-n : print the last lines the default is 10
+n : prints the lines from nth line to end of file
$ tail dolls [ displays last 10 lines of dolls file ]
$ tail -5 dolls [displays last 5 lines from dolls file ]
$ tail –c5 dolls [ displays last 5 characters (includes whitespace)]
usage
ls | tail -15 [ displays last 15 lines of file listing]
head abc | tail -5 [ prints lines 6 through 10 of file abc]
cut: This command is used to cut the file vertically i.e to copy (display) the specified
columns to the standard output file. This command can be used to cut out parts of a file .
it takes filenames as arguments. It can cut columns or fields in a file. However it does not
delete the selected parts of the file
Options
-b list : to specify the bite position
-c list : to extract the characters as specified position in the list . a dash (–) is used
to indicate the range and comma(,) is used to separate items in the list.
-f list : to extract the fields as specified position in the list. a dash (–) is used to
indicate the range and comma(,) is used to separate items in the list.
-dc : the character following the d is field delimiter and this option is used only
with -f option
$ cut -c 10-15 stdlist
$ cut -d”:” –f 1,3 stdlist
paste: This command is used to combine two or more files vertically. The lines of the
input files must be in corresponding order before the paste utility can be used. If there is
no corresponding field the command puts the delimiter and leaves it blank.
Options
-dc : to specify the delimiter character used in combined file
Note: paste expands table’s (file’s) width by increasing the number of columns. But cat
expands a table’s length by increasing the number of rows.
uniq: This command is used to remove the repeated lines from a file. The file must be in
sorted order before using this command.
Options
-c: precedes each line in o/p with count of number of times the line occurred in i/p
file
-d: selects only one copy of the duplicate entries
-u:selects lines which are not repeated
-i: ignore case
$ uniq names
$ uniq -c names
$ uniq -u names
tr: This command is used to translate characters. This command manipulates individual
characters in a line. It takes input only from standard input. The syntax is:
wc: this command is used to count the number of lines ,words and characters in one or
more files. It gives 4 column output, where the first column indicates number of lines in
the file, second column indicates number of words, the third indicates number of
characters and the last column indicates the file name.
Options
-c: it prints the counts of characters
-w: it prints the counts of words
-l : it prints the counts of lines
$ wc fruits
$ wc -c fruits
$wc -w fruits
Page4
$wc -l fruits
sort: this command is used to sort the contents of a file. Using this utility one or more
files can be sorted in alphabetic or numeric order, and also it can reorder the file based
on one or more of the fields.
Options
-d : sorts according to dictionary and ignores punctuation.
-f:ignores caps while sorting
-m : merges two or more given sorted files tnto single sorted file
-n : sorts according to numeric order
-r : sorts in reverse order
-u : removes duplicates and displays unique values
-o : specifies output file name
-t : specifies the delimiter used in the file
-k fieldno : sorts the data according the field number specified by the fieldno
$ sort file1
$ sort -o sfile file1
$ sort -r file1
grep: this command is used to searches its input for a pattern and displays lines
containing the pattern (Globally search a Regular Expression and Print it) . The syntax is:
grep [options] [pattern] [file name]…..
the pattern can be a string with single or multiple words or special characters. It is
advised to enclose the pattern with single codes.
Options
-e : pattern : to specify multiple search pattern.
-i : prepares case while searching.
-n: used to display records (lines) along with line number
-v: prints those lines which do not match the pattern
-c: displays only the count of lines which contains pattern
-l: displays only the names of files containing the pattern
$ grep “bca” stdlist
$ grep -i “bca” stdlist
$ grep -n “BCA” stdlist
grep family contains three commands namely grep, egrep(extended grep) and
fgrep(fixed grep)
The egrep command treats the meta-characters as they are and do not require to be
escaped as is the case with grep. This allows reducing the overhead of replacing these
characters while pattern matching making egrep faster than grep or fgrep.
Syntax:
egrep [options] '<regular expression>' <filename>
Some common options are:
-c for counting the number of successful matches and not printing the actual matches
-i to make the search case insensitive, -n to print the line number before each match
printout
-v to take the complement of the regular expression (i.e. return the lines
which don't match),
-l to print the filenames of files with lines which match the expression.
fgrep : This command searches for fixed-character strings in a file or files. "Fixed-
character" means the string is interpreted literally — metacharacters do not exist, and
therefore regular expressions cannot be used.
fgrep is useful when you need to search for strings which contain lots of regular
expression metacharacters, such as "$", "^", etc. By specifying that your search string
contains fixed characters, you don't need to escape each of them with a backslash.
$ egrep ‘bca
Bcom
bsc’ studfile
$ egrep –i ‘bca
bcom’ studfile
expressions with opposing functions. The vertical bar separates the expressions while the
parentheses operator groups them.
tar
The Linux ‘tar’ stands for tape archive, is used to create Archive and extract the Archive
files. tar command in Linux is one of the important command which provides archiving
functionality in Linux. We can use Linux tar command to create compressed or
uncompressed Archive files and also maintain and modify them.
Syntax:
tar [ptions] filename
Options:
-c : Creates Archive
-x : Extract the archive
-f : creates archive with given filename
-t : displays or lists files in archived file
-u : archives and adds to an existing archive file
-v : Displays Verbose Information
-A : Concatenates the archive files
-z : zip, tells tar command that create tar file using gzip
-j : filter archive tar file using tbzip
-W : Verify a archive file
-r : update or add file or directory in already existed .tar file
An Archive file is a file that is composed of one or more files along with metadata. Archive files
are used to collect multiple data files together into a single file for easier portability and storage,
or simply to compress files to use less storage space.
Examples:
Creating an uncompressed tar Archive using option -cvf : This command creates a tar
file called file.tar which is the Archive of all .c files in current directory.
$ tar cvf file.tar *.c
Extracting files from Archive using option -xvf : This command extracts files from
Archives.
$ tar xvf file.tar
gzip compression on the tar Archive, using option -z : This command creates a tar file
called file.tar.gz which is the Archive of .c files.
$ tar cvzf file.tar.gz *.c
Extracting a gzip tar Archive *.tar.gz using option -xvzf : This command extracts files
from tar archived file.tar.gz files.
$ tar xvzf file.tar.gz
Creating compressed tar archive file in Linux using option -j : This command
compresses and creates archive file less than the size of the gzip. Both compress and
decompress takes more time then gzip.
$ tar cvfj file.tar.tbz example.cpp
untar single tar file or specified directory in Linux : This command will Untar a file in
current directory or in a specified directory using -C option.
$ tar xvfj file.tar
Untar multiple .tar, .tar.gz, .tar.tbz file in Linux : This command will extract or untar
multiple files from the tar, tar.gz and tar.bz2 archive file. For example the above
Page7
Chapter 4
Process management
Process :- Process can be defined as a program under Execution. Unix runs many programs at the
same time by using Round-robin Scheduling algorithm.
The shell process(sh) is a parent process and the cat process is a child process. As long as process is
running, it is alive. After completing the job, it becomes inactive and is said to be dead.
The shell creates two child process cat and grep simultaneously.
Process state:-
3) Waiting : The process is waiting for some required resources like input and output devices
4) Ready : The process is waiting to be allocated to a processor. The process comes to this state
immediately after creation.
2)
ii. Ready (Swapped):- Ready to run, but needs to be swapped into memory.
3)
i. Asleep (in memory):- The process is blocked and waiting for an event in
memory.
ii. Asleep (swapped):-The process is swapped out and waiting for an event on the disk.
6) Zombie:- A zombie process in UNIX is a process that has terminated, but whose parent has not waited
for it. May be a parent process exited without waiting for it to terminate
7) Pre-empted:- is a process returning from kernel mode to user model, since it in preempted by kernel,
to schedule another process.
★ Parent is the
orginal process.
★ the parent can either wait for child to complete , or continue executing in parallel with the
child.
★ Resource sharing: a process needs certain resource like CPU time, Memory, I/O devices etc.
★ exec( ) system call is used after fork( ), to start another different program.
1.inter-active (foreground)process:-
All the processses creted by the user using the shell and atached to the terminals are called fore
ground process.
-> when user pass a command to shell ,the shell passes ,rebuilds and sends it to the kernal for execution.
-> duiring the execution of one process the user should wait for the kernal until compilatiton of that
process.
2.non-interactive(background)process:-
The process which can without using the terminal are know as background process.
-> background process take input from a file ,process them without holding up the terminal and write
output on other file.
-> for ex:- sorting and searching of files/content from long files.
limitatitons:-
-> nohup (no hang up) which avoids deadlocking of ome background process during unusual logouts.
runaway process :- when background process (using & at the end) and logout without closing or
killing the process .such a processs is called runaway process.
the value range from 0 to 39, in linux -9 to 20 .where 0 is high and 39 is lower value.
the priority of a process can be increased only by adminstrator using double minus(--).
The priority of a process can be made lower using the nice command.
for example: if a process is already running and using a lot of cpu time; then it can be reniced.
Daemon Processes:-
Daemon processes are processes that are constantly running without using associated terminal or login
shell, and keeps waiting for some instructions either from the system or user and immediately starts
performing that task.
★ Process vhand, which stands for virtual memory handler, is loaded into the system to swap the active
processes between memory and disk, when they are waiting for CPU time.
Process Termination:-
There are situations when the user has to terminate a process prematurely. Several reasonS are
possible for process termination such as:
★ Memory unavailable
★ I/O failure.
★ Data misuse.
Communication commands:-
1) kill command:
Syntax:- $ finger
5) wall command:- wall stands for write all. Wall command is used only by
the super user to send messages to all users on the system.
Syntax:- $ wall
★★★★★
- r w x r - - r - -
0 1 2 3 4 5 6 7 8 9
Numeric representation:
If a numeric representation is used (like in chmod command) then it is in the
octal format(base of 8)
Digits involved are 0 to 7. Every octal digit combines read, write and execute
permission together,respective access rights for owner, group and other are
the last three digits of the numeric file permissions representation .
The head command display the first few lines of one or more file .this
command is used to verify the contents of a file. Without any option. By
default it display the first 10 lines of the file
Options:
The tail command displays the last few lines of a file .by default, it displays
the last 10 lines of the file. It connot be used for multiple files
WC:
Wc options:
-w: counts words delimited by white space character or new line character.
Cut command :
Sort :
The sort command is used to sort the information in a text file in ascending
or descending order .it is also used to merge sorted files it takes zero, one
or more filename as arguments
Sort option :
Sort command has several options .some of the most command options are
given below.
Grep options :
It works the same way as grep –e das it treats the pattern as an extched
regular expressions and prints out the lines that match the pattern.
It there are several files with the matching pattern it also displaythe file
name for each line.
The e-grep command used mainly due to the fact that it is faster than
grepcommand.the grep command treats the meta character they are
[Type text] Page 5
Syntax:egrep[option]<regular expr><filename>
-c :for counting the number of successful match and not printing the
actual matches.
-l : to print the file names of files with lines which match the
expression.
f-grep
the command when you need to search for string which contain lots of
regular expressions meta character $ and ^etc. by specifying that your
search and strings contains fixed character you donot need to escape
each of then with a (back slash \)
Chapter-6
Shell Programming
The shell provides you with an interface to the UNIX system. It gathers input from
you and executes programs based on that input. When a program finishes executing, it
displays that program's output.
A shell is an environment in which we can run our commands, programs, and shell
scripts. There are different flavors of shells, just as there are different flavors of
operating systems. Each flavor of shell has its own set of recognized commands and
functions.
Shell Prompt:
The prompt, which is called command prompt, is issued by the shell. While the prompt is
displayed, you can type a command.
The shell reads your input after you press Enter. It determines the command you want
executed by looking at the first word of your input. A word is an unbroken set of
characters. Spaces and tabs separate words.
Following is a simple example of date command which displays current date and time:
$date
Shell Types:
1. The Bourne shell. If you are using a Bourne-type shell, the default prompt is the
$ character.
2. The C shell. If you are using a C-type shell, the default prompt is the %
character.
There are again various subcategories for Bourne Shell which are listed as follows:
• C shell ( csh)
• TENEX/TOPS C shell ( tcsh)
The original UNIX shell was written in the mid-1970s by Stephen R. Bourne while he
was at AT&T Bell Labs in New Jersey.
The Bourne shell was the first shell to appear on UNIX systems, thus it is referred to as
"the shell".
The Bourne shell is usually installed as /bin/sh on most versions of UNIX. For this
reason, it is the shell of choice for writing scripts to use on several different versions of
UNIX.
Shell Scripts:
The basic concept of a shell script is a list of commands, which are listed in the order
of execution. A good shell script will have comments, preceded by a pound sign, #,
describing the steps.
There are conditional tests, such as value A is greater than value B, loops allowing us
to go through massive amounts of data, files to read and store data, and variables to
read and store data, and the script may include functions.
Shell scripts and functions are both interpreted. This means they are not compiled.
Example Script:
Assume we create a test.sh script. Note all the scripts would have .sh extension.
Before you add anything else to your script, you need to alert the system that a shell
script is being started. This is done using the shebang construct. For example:
#!/bin/sh
This tells the system that the commands that follow are to be executed by the Bourne
shell. It's called a shebang because the # symbol is called a hash, and the !symbol is
called a bang.
To create a script containing these commands, you put the shebang line first and then add the
commands:
#!/bin/bash
pwd
ls
Shell Comments:
#!/bin/bash
# this is sscasc
# Copyright (c)
sscasc.com #
Script follows
here: pwd
ls
Now you save the above content and make this script executable as follows:
$chmod +x test.sh
follows: $./test.sh
The shell is, after all, a real programming language, complete with variables, control
structures, and so forth. No matter how complicated a script gets, however, it is still just
a list of commands executed sequentially.
Following script use the read command which takes the input from the keyboard and
assigns it as the value of the variable PERSON and finally prints it on STDOUT.
echo "What is
your name?"
read PERSON
echo "Hello,
$PERSON"
$./test.sh
What is your
name? vvfgc
Hello, vvfgc
Variables:
Variable is value that always changes during execution of a program. It is an integral part of
shell programming. They provide the ability to store and manipulate information.
• Environment variables
• User defined variables
Environment variables:
These variables are the part of the system and these are created and maintained by the
syatem itself. These variables always in capital letters only.
Variable meaning
variable_name = variable_value
For example:
NAME = "sscasc"
Above example defines the variable NAME and assigns it the value "sscasc". Variables
of this type are called scalar variables. A scalar variable can hold only one value at a
time.
The shell enables you to store any value you want in a variable. For example:
VAR1="ssczsc "
VAR2=100
To access the value stored in a variable, prefix its name with the dollar sign ( $):
For example, following script would access the value of defined variable NAME and
would print it on STDOUT:
NAME="v
vfgc "
echo
$NAME
Output: vvfgc
Read-only Variables:
The shell provides a way to mark variables as read-only by using the “read only”
command. After a variable is marked read-only, its value cannot be changed.
For example, following script would give error while trying to change the value of NAME:
NAME="vvfg
c "readonly
NAME
NAME="Qadiri"
Unsetting Variables:
Unsetting or deleting a variable tells the shell to remove the variable from the list of
variables that it tracks. Once you unset a variable, you would not be able to access
stored value in the variable.
Above command would unset the value of a defined variable. Here is a simple example
NAME="v
vfgc"
unset
NAME
echo
$NAME
Above example would not print anything. You cannot use the unset command to unset
variables that are marked readonly.
Read command
The variable used along with the read command need not be preceded by the
$ symbol. Ex: clear echo “enter ur name” read name echo “hello
$name”
Hello vvfgc
Expr command
Where ( ` ) this symbol is known as grep symbol. There is always must a space
between symbol and the expr command. Ex: clear echo “enter 2 numbers”
read a b
$b ` “ Note:
In unix multiplication purpose we use the symbol of “\*” because only * is wild card
character.
Arithmetic Operators:
Show Examples
Equality - Compares two numbers, if both are [ $a == $b ] would return same then
==
returns true. false.
Not Equality - Compares two numbers, if both [ $a != $b ] would return are
!=
different then returns true. true.
It is very important to note here that all the conditional expressions would be put inside
square braces with one spaces around them, for example [ $a == $b ] is correct where as
[$a==$b] is incorrect.
Bourne Shell supports following relational operators which are specific to numeric values.
These operators would not work for string values unless their value is numeric.
For example, following operators would work to check a relation between 10 and 20 as well
as in between "10" and "20" but not in between "ten" and "twenty".
Show Examples
It is very important to note here that all the conditional expressions would be put inside
square braces with one spaces around them, for example [ $a <= $b ] is correct where as
[$a <= $b] is incorrect.
Show Examples
Assume a variable file holds an existing file name "test" whose size is 100 bytes and has
read, write and execute permission on:
Show Examples
Operator Description Example
Checks if file is a block special file if yes then
-b file [ -b $file ] is false.
condition becomes true.
Checks if file is a character special file if yes
-c file [ -b $file ] is false.
then condition becomes true.
Check if file is a directory if yes then condition
-d file [ -d $file ] is not true.
becomes true.
Check if file is an ordinary file as opposed to a
-f file directory or special file if yes then condition [ -f $file ] is true.
becomes true.
Checks if file has its set group ID (SGID) bit
-g file [ -g $file ] is false.
set if yes then condition becomes true.
Checks if file has its sticky bit set if yes then
-k file [ -k $file ] is false.
condition becomes true.
Checks if file is a named pipe if yes then
-p file [ -p $file ] is false.
condition becomes true.
Checks if file descriptor is open and associated
-t file with a terminal if yes then condition becomes [ -t $file ]
is false. true.
Checks if file has its set user id (SUID) bit set
-u file [ -u $file ] is false.
if yes then condition becomes true.
Checks if file is readable if yes then condition
-r file [ -r $file ] is true.
becomes true.
Check if file is writable if yes then condition
-w file [ -w $file ] is true.
becomes true.
Check if file is execute if yes then condition
-x file [ -x $file ] is true.
becomes true.
Check if file has size greater than 0 if yes then
-s file [ -s $file ] is true.
condition becomes true.
Check if file exists. Is true even if file is a
-e file [ -e $file ] is true.
directory but exists.
Control statements
The ability to control the flow of execution of program is known as control statements.
This type of instruction allows the shell script to be executed depending on the condition.
• if-then-fi statement
• if-then-else-fi statement
• if-then-elif-then-else-fi statement case-esac statement if-then-fi statement:
in this first check the condition. That condition is true then only the if block statements
will be executed otherwise the cursor transfer outside the if condition.
Syntax: ex:
if [ condition ] if [ $a –gt 18 ]
then then
fi fi
if-then-else-fi statement:
in this first check the condition. That condition is true then only the if block statements
will be executed otherwise the else block statements will be executed.
Syntax: ex:
if [ condition ] if [ $a –gt $b ]
then then
else else
fi fi
if-then-elif-then-else-fi statement:
in this first check the condition. That condition is true then only the if block statements
will be executed otherwise the cursor checks the next condition then the second
condition will be true then inside that statements will be executed and so on. If any
conditions were not true then the else block statements will be executed.
Syntax: ex:
then then
then then
else else
fi fi
Case-esac statement:
[match1] )statements ; ;
[match2] statements ; ;
[match3] statements ; ;
: :
: :
*) statements ; ;
esac
readch
case $ch in
esac
• While loop
• Until loop
• For loop
While loop:
This is the pretested loop or entry controlled loop. In this first check the condition, if
that condition was true then control enter inside the loop otherwise control transferred
outside the loop.
Syntax: ex:
do do
done
until loop:
This is also pretested loop or entry controlled loop. In this first check the condition, if
that condition was false then control enter inside the loop otherwise control transferred
outside the loop.
Syntax: ex:
do do
done i =`
expr $i + 1 `
done
for loop:
This is a fixed execution loop. This loop is allow to execute list of statements certain
period of time.
Syntax:
….. value n do
statements
done
ex:
for i
in 1 2
345
do
echo $i
i=` expr $i + 1 `
done