Professional Documents
Culture Documents
UNIX
Version 1.0
UNIX Operating System
Features :
Multiuser & Multiprocessor System
Time Sharing Operating System
Written in “C” (HLL)
has all advantages of HLL
performance low compared with HLL
Simple User Interface
Hierarchical File System
Consistent File Format - the Byte Stream
Supports Languages - FORTRAN, BASIC, PASCAL, Ada, COBOL, LISP,
PROLOG, C, C++
System V - about 64 system calls
Unix/Intro/01
Architecture of UNIX System
Cpp Sh
wh
o
nroff
Kernel
A.cut
comp
Hardware da t
CC e
os
m
wc
ra
og
pr
vi
n
tio
ed grep
ica
pl
ap
er
th
O
Unix/Intro/02
Unix O.S.
Services Provided :
Process Management - Creation, Termination or Suspension and
Communication
CPU Scheduling
Memory Management - Swapping & Paging
File Management
Peripheral Device controlled access to process - terminal, printer, tape
Unix/Intro/03
File System
A Hierarchical Structure
Unix/Intro/04
File System
/ (Root)
cmd
Date.c Who.c
Unix/Intro/05
File System
File Types
Directory File
Regular File
Device File
Classes of User
Owner
Group
Others
Access Permission
Read
Write
Execute
Unix/Intro/06
File System
Consists of Sequence of Logical Blocks
An Installation may have
each containing one or more file system
File System Treated as Logical Device (Logical Device Number)
Data from another File System can be Accessed by Mounting that File System
Unix/Intro/07
File System Layout
Boot Block
Super
Block
Inode List
Data
Blocks
Unix/Intro/08
File System
Boot Block
Beginning of File System (1st Sector)
Contains Bootstrap Code
Every File System has (possibly empty) Boot Block
Super Block
Size
# of Files that can be Stored
Free Space Information
Inode Information
Inode List : Information about each inode e.g. access permissions, data/time,
phy. Addr. Etc.
Data Block : File Data & Administrative Data
Unix/Intro/09
File System
Inode Table Fields :
Date & Time - Last File/Inode Modified/Accessed
No. of Links
Disk Addresses
File Size
Unix/Intro/10
File System
Directories
File Names
83 . Current Directory
2 .. Parent Directory
1798 Init
1799 mount
2114 passwd
:
0 crash
: :
Unix/Intro/11
Building Block Primitives
1. Each Process has Access to 3 Files
standard input (“<“)
standard output (“>”)
standard error (“2>”)
e.g.
$ls
$ls>temp
$cat >test
$cat ->test
$cat >>test
$catt ->>test
Unix/Intro/12
Building Block Primitives
2. Pipe - allows stream of data to be passed between reader &
writer process
b) $who| wc-l
c) $ls|wc-l
d) $ls|wc-l>fcount
Unix/Intro/13
Building Block Primitives
3. Tee - standard output can be saved in a file as well as displayed
$_
Unix/Intro/14
File System
The Structure of File System
Root (/)
<files> <files>
Unix/Intro/15
File System
/ bincommonly used UNIX Command like
temporary files
/usr - contains all the files created by user, including login directory
/unix - kernel
Unix/Intro/16
Basic Commands - pwd, cd
$pwd
/usr/Kumar
e.g. $pwd
/usr/Kumar
$cd Prog
$pwd
/usr/Kumar/Prog
e.g. $cd
Unix/cmd/01
Basic Commands - logname, cat
$cd /usr/Sharma
$logname
Kumar
$_
01|accounts|6213
02|admin|5423
06|training|1006
$_
Unix/cmd/02
cat Command
Scrolling of large files can be freezed by pressing <ctrl s> and resumed by
<ctrl q>
e.g. $cat>test
Type here the text contents
After typing the entire text
Press <ctrl d> to save and exit
<ctrl d>
$_
Unix/cmd/03
ls Command
e.g. $ls
a.out
chap1
chap2
test
test.c
$_
Unix/cmd/04
ls Command
Options available in ls
Option Description
Unix/cmd/05
ls Command
E.g.
$ls - l
total 8
_rw_rw_rw_ 1 Kumar group 44 May 9 09:08 dept.h
_rw_rw_rw_ 1 Kumar group 212 May 9 09:08 dept.q
_rw_rw_rw_ 1 Kumar group 154 May 9 09:08 emp.h
_rw_rw_rw_ 1 Kumar group 742 May 9 09:08 emp.q
$_
File type
- --> regular file
d --> directory file
c --> character - read
b --> block read
--> user permissions
--> group permissions
--> others permissions
Unix/cmd/06
ls Command
Field4 - Group id
Field7 - Filename
The total field at the beginning indicates total no. of block occupied by these
files
Unix/cmd/07
mkdir Command
Creates a directory
Unix/cmd/08
rmdir Command
More than one dir can be deleted in single command
Command should be executed from at least one level above in the hierarchy
Unix/cmd/09
chmod Command
Used to alter file permissions
Format :
permission
a-all
Unix/cmd/10
chmod Command
E.g. $chmod u+x note
$ls - l note
-rwx r-- r -- 1 …… note
Unix/cmd/11
chmod Command
Octal notation
describes both category and permission
similar to =operator (absolute assignment)
read permission - assigned value is 4
write permission - assigned value is 2
Execute permission - assigned value is 1
Unix/cmd/12
cp Command
Copies a file or group of files
Option - i (interactive)
$cp - i chap1 chap2
cp: overwrite chap2 ? y
Unix/cmd/13
rm Command
To delete files
e.g. $rm chap1 chap2 chap3
$rm chap*
$rm *
Are you sure? y
Unix/cmd/14
mv Command
Used to rename file or group of files
directory
Unix/cmd/15
more Command
Allows user to view a file one screen at a time
Syntax :
more <options <+linenumber> <+/pattern> <filename>
: appears after displaying screen
<spacebar> or <enter> - next screen
q - quit
n - switch to next file on command
p - switch to previous file
f - displays filename and line no.
/pattern - to locate line with pattern
! - to run command
Unix/cmd/16
more Command
Command Description
Unix/cmd/17
wc Command
Counts lines, words and character depending on option
takes one or more filename as arguments
e.g. $wc infile
3 20 103 infile
$wc infile test
3 20 103 infile
10 100 180 test
13 120 283 total
$wc - l infile
3 infile
$wc - w infile
20 infile
$wc - c infile
103 infile
$wc - wl infile
20 3 infile
Unix/cmd/18
od Command
options
Unix/cmd/19
cmp Command
option -l gives detailed list of byte no. and different byte in octal
3143 145
6170 167
7171 170
Unix/cmd/20
comm Command
Unix/cmd/21
diff Command
display which lines in one file have to be changed to make both files identical
second
option -b consecutive blanks considered as one blank and trailing blanks are
ignored
Unix/cmd/22
banner Command
Unix/cmd/23
cal Command
$cal 01 1991
Unix/cmd/24
date Command
Displays system date
number of options available
option m - month
h - month name
d - day of month
y - last two digit of the year
H - hour
M - minute
S - second
T - time in hh:mm:ss
a - day of week (Sun to Sat)
r - time in AM/PM
e.g. $date
Fri Dec 7 15:00:21 EST 1990
$date +%m
12
$date +”%h%m”
Dec 12
$date “+The day of week is %a and time y.r”
The day of week is Fri and time 03:23:42 PM
Unix/cmd/25
who Command
e.g. $wo
columns
Unix/cmd/26
Terminal Related Commands
<Del> key
Unix/cmd/27
head Command
Displays the beginning of a file
also works with multiple files
e.g. $head -3 emp.lst
will display first 3 lines
tail command
displays the end of a file
default - display last 10 lines
$tail -3 emp.lst
displays last 3 lines
$tail +50 emp.lst
displays till end of file starting from line no. 50
max. 4096 char segment can be displayed
if size specified is greater than 4096 then last 4096 char are displayed
Unix/cmd/28
tail Command
$tail -15c emp.lst
display last 15 characters
Unix/cmd/29
Cut & Paste Commands
Cut :
Allows you to slice the file vertically
Unix/cmd/30
Cut & Paste Commands
Paste :
paste more than one file laterally
$paste file1 file2
<…file1> <file2>
delimiter can be inserted between two files
Unix/cmd/31
sort Command
$sort <file> …. Sorts entire line
reorders a line in a ASCII collating sequence
sorting can be done on a field
delimiter can be specified, -t option
$sort -t “|” +1 emp.lst
Unix/cmd/32
sort Command
$sort -m file1 file2 file3
merges sorted files
Numeric Sort
$sort -n file1
Option -b ignores leading blank spaces
-d Alphanuemric sort
- f folds uppercase into lowercase
Uniq Command
removes duplicate records (-d option)
$uniq dept.lst
$sort dept.lst | unique - uniqlst
-u option if only unique records to be listed
-d if only one copy of repeated records to be selected
Unix/cmd/33
nl Command
nl - line numbering command
$nl empl.lst
1 1001 …..
2 1002 …..
:
:
width of line number can be specified
-w option
-s (separator) can be specified
-n leading zeros in line number
$nl -w2 -s “|” -nrz emplst
Unix/cmd/34
grep Command - Advanced Filter
Searches for a given pattern in the files specified
grep <options> <pattern> <filename(s)>
Options
-c displays count of occurrences
-l displays list of filenames only
-n displays line number along with lines
-v displays all but the line matching pattern
-i ignores case
-h omits filename
-f fname reads expression/pattern from file
(egrep & fgrep option)
-x displays lines match in entirety
(fgrep option)
Unix/cmd/35
grep Command
e.g. $grep sales emp.lst
$str = ‘sales’
Unix/cmd/36
Regular Expressions
Used to specify pattern
specified in single quotes
Expression
ch* - 0 or more occurrence of char ch
ch \ {m\} - matches m occurrence of char ch
ch \ {m,n\} - matches min. m & max. n occurrence
of char ch
ch \ {m,\} - matches min. m occurrence
[pqr] - matches single char p, q or r
[c1-c2] - match single char within ASCII range
specified
[^pqr] - matches single char which is not p, q
or r
\(ptn\) - matches pattern ptn enclosed in \(,\)
with the tag \n (n ranges 1 to 9)
e.g. ` \ (.. \) \1`
Unix/cmd/37
Expression
^ptn - matches pattern ptn at beginning of line
ptn$ - matches pattern ptn at end of line
e.g. Consider following R.E.
(i) ‘[cC]ho [wu]dh*ury’
(ii) ‘[7-9] …$’ char [7-9] followed by 3 more
chars rep by … at end of line
(iii) ‘director.*[7-9]…$’
(iv) ‘^[\t]*$’
(v) ‘^ ……… 03’
.\{10\}
(vi) [0-9] [0-9] [0-9] [0-9]
Unix/cmd/38
egrep Command
egrep - Extending grep
extends grep pattern matching capabilities
Extending R.E. features
ch+ matches 1 or more char ch
ch? Matches or 1 char ch
exp1/exp2 matches exp1 or exp2 expression
(x1/x2)x3 matches expression x1x3 or x2x3
x1/x2 matches expression x1 or x2
Unix/cmd/39
fgrep Command
$cat pat.lst
sales
admin
Unix/cmd/40
Process Status
$ps - give pid, tty, time, command
options
-f - full from (additional - user-id parents pid,
CPU time consumed, start time
cumulative process time)
-u - details of only users processes
-a - all processes details
-l - detailed listing
-e - system processes
Background Process
$sort -0 emp.lst emp.lst &
$a.out &
nohup (no hangup) - permits execution of process even if user has logged
off
$nohup sort emp.lst &
sends output to nohup.out
Unix/cmd/41
Process Related Commands
Wait
shell command
waits for child process to complete
$wait 138 - waits for background job with pid 138
Kill
$kill 1005 (default signal 15)
kills job with pid 1005
$kill -9 1005
Unix/cmd/42
Editors
Three Types
Screen Editor - vi
Unix/vi/01
vi Editor
Three Modules :
Command
i, I, a, A, Mode
r, R, o, O, :
s, S
<Enter>
sh
<Esc>
<ctrl d>
Input or exit
ex
command
Mode
Mode
:set showmode
displays message when in input mode
Unix/vi/02
vi Editor - Save & Quit
From input mode ZZ
From input mode to command mode press <Esc> and from command mode
To Save :w
To Quit :q
or :x
Unix/vi/03
vi Editor - Command Mode
Deletion
x - single char
dd - line delete
Unix/vi/04
vi Editor - Navigation
Unix/vi/05
vi Editor - Other Features
Joining line
Marking Text
line
Reverse all changes made to current line - U
Unix/vi/06
Input Mode Commands
Command Function
Unix/vi/07
Cursor Movement Commands
Command Function
Unix/vi/08
Paging Functions
Command Function
factor)
Unix/vi/09
Search and Repeat Commands
Commands Functions
Unix/vi/10
A Few Specimen Operator-Command Combinations
Command Function
Unix/vi/11
Command Function
Unix/vi/12
Set Options Used by ex/vi
Option Abbreviation Significance
Unix/vi/13
Advanced Filter - awk
Report writer
named after Aho
Weinberger
Kernigham
As powerful programming language
awk pgm are slow
It can access, transform and format individual fields in a record
Syntax
awk <options ‘line specifier {action}’ <files>
Unix/awk/01
Advanced Filter - awk
Line specifier and action option are optional, either of them needs to be
specified
line specifier not specified indicates all lines to be selected
{action} omitted indicates print (default)
fields are identified by special variable
$1, $2, ….; default delimiter is contiguous string of spaces
Explicit delimiter can be specified using -F option
e.g. awk -F “|” ‘/sales/{print $3, $4}’ emp.lst
Regular expression of egrep can be used to specify pattern
Line numbers can be selected using NR built-in variable
$awk -F “|” ‘NR ==3, NR ==6 {print NR, $0}’ emp.lst
Unix/awk/02
awk Command
Output can be formatted using printf
similar to printf in ‘c’ but not a function
e.g. $awk -F “|” ‘/[aA]gg?[ar]+wal/{
>printf “%3d%-20s%-12s%d\n”, NR, $2,$3,$6}’
>emp.lst
Record no./
Line number
will be printed
, (comma) to be used as delimiter in printf
Logical and Relational operators
Logical operator &&, ||
$awk - F “|” ‘$3 ==“director” || $3 == “chairman”{
>printf “%-20s”,$2}’ emp.lst
== tries to find perfect match but string may have trailing spaces to overcome this ~ and !~
(match & negate of match) can be used with R.E.
Unix/awk/03
awk Command
e.g.$awk -F “|” ‘$2~/director/||$~/g.m/{
>printf $0}’ emp.lst
e.g.$3 ~/^g.m/
Unix/awk/04
awk Command
-f option
awk program can be written in a separate file and used in awk
Unix/awk/05
awk Command
e.g. $cat emp.awk
BEGIN {
printf “\n\t Employee details \n\n”
}
$6>7500{
# increment sr. no. and sum salary
kount++; tot+=$6
printf “%d%-20s%d\n”, kount, $2, $6
}
END {
printf “\n The Avg. Sal. Is %6d\n”, tot/kount
}
$_
&awk -F “|” -f emp.awk emp.lst
Unix/awk/06
awk Command
Positional parameters and shell variable
(i) Method I
requires entire awk command should be in the shell script
to differentiate positional parameter and field identifier, the positional
parameter should be single quoted in awk program
e.g. $3 > ‘$1’
(ii) Method II
store entire command sequence in separate script file
shell can pass values to awk
e.g. awk pgm
$6 > mpay { … }
$awk - F “|” -f emp.awk mpay = 7800 emp.lst
assignment should be immediately before filename
Unix/awk/07
awk Command
e.g. List the details of employee drawing salary
greater than avg. salary
Unix/awk/08
nawk - getline Statement
awk uses i/p from standard input or file
nawk - i/p from standard input device & file possible (at beginning)
when getline is execute the contents of next line gets stored in var.
e.g. getline x
Unix/awk/09
Built-in Variable
NR - Cumulative no. of records read
Unix/awk/10
Arrays
Can handle single dimension array
index can be anything even string
no declaration required, initialized to zero automatically
e.g. totl[1] +=$6; tot[2]+=da; tot[3]+=HRA; temp[$3]
Functions
Unix/awk/11
Interface with Shell
Redirection > , piping | possible
restriction - filenames, commands that follows these symbol must be in double quotes
unix commands can be run within nawk using system function
e.g. BEGIN {system (“date”)}
Control FLOW :
(I) if … then …
if (conditions is true)
<statements>
else
<statements>
Unix/awk/12
Interface with Shell
(iii) for loop for arrays
for (k in array)
<commands>
Unix/awk/13
Shell
Shell - The agency that sits between user and
UNIX System
- widely used
C Shell - product from Univ. of California, Berkeley
features
Korn Shell - by David Korn of Bell Lab.
Unix/sh/01
echo Command
Displays argument
e.g. $echo GOOD Morning
GOOD Morning
$echo \*
*
$echo ‘*’
*
escape sequence to manipulate cursor position
\t : tab
\f : formfeed
\n : newline
\c : cursor immediately after argument
e.g. $echo ‘Enter Your Name : \c’
Enter Your Name : $_
accepts ASCII Octal values
e.g. $echo ‘\007’
<… beep hear…:
Unix/sh/02
Command Substitution
Command enclosed in backquotes (`), the shell executes the command first,
and the enclosed command text is replaced by the output of the command
sequentially
directory”
Unix/sh/03
Shell Variables
User variables can be defined
no type declaration or initialization
Format : variable=value
Value is of string type
No space preceding and following =operator
Evaluated by prefixing variable name with $
multi word assignment must be quoted
e.g.1 $x = 37
$echo $ x
37
e.g.2 $msg = You have mail
have not found
e.g.3 $msg = ‘You have mail’
$echo $msg
You have mail
Unix/sh/04
Shell Variables
4. $msg = You\ have\ mail
$echo $msg
You have mail
5. $x = aa
$y = bb
$echo $x$y
aabb
6. $echo ‘Amount = $1000’
$echo Amount = \$1000
- both will display : Amount =$1000
$echo “Amount = $1000”
Amount=000
- here shell evaluated variable $1 as double
quoted
Unix/sh/05
Shell Variables
7. $p = `pwd`
$echo $p
8. $echo ${fname}
emp.sh
$echo ${fname}x
emp.shx
Unix/sh/06
Shell Variables
System Variables
Set during - booting
- login
script executed during login time - profile
profile alters operating environment of a user
to display list of system variable $set
list of variable
PATH - list of dir. In order of precedence that have to be scanned for hunting
command
Home - dir. Named after Login name
IFS - string of char which are used as word separator in the command line
MAIL - mail directory
PS1 - Two prompts - primary and secondary
PS2 - (used by sed, awk)
TERM - Terminal type
Unix/sh/07
Shell Variables
indicate end of
document
>mark
Unix/sh/08
Read Statement
Takes input from standard i/p
can be used to read one or more variables
OR
echo “\n Enter pattern & file name : \c”
read patname fname
Unix/sh/09
Command Line Arguments
Shell procedures arguments in command
Arguments are specified along with the name of shell procedure
Arguments are assigned to special variables (positional parameters) $1 - First
parameters
$2 - Second parameters
:
:
Special parameters also available
$0 - Name of executed command
$* - Complete set of positional parameters
$# - No. of arguments
$$ - PID of current shell
$! - PID of last background job
$? - Exit status of last command
$@ - Same as $* except when enclosed in double quotes
Unix/sh/10
Command Line Arguments
E.g.1 if [$# -nc 3]
then
:
:
fi
2 $kill - 9 $$
3 grep “$1” $2
Unix/sh/11
Conditional Execution
Logical Operators && and ||
&& operator delimits two commands, the second command is executed only if first succeeds
|| operator delimits two commands, the second command is executed only if first fails
Unix/sh/12
if Statement
Format :
(i) if <condition is true>
then
<execute commands>
else
(execute commands>
fi
(ii) if <condition is true>
then
<execute commands>
fi
(iii) if <condition is true>
then
<execute commands>
elif <condition is true>
then
<execute commands>
<…>
<…>
else
<execute commands>
fi
Unix/sh/13
if Statement
Condition can be specified either using test or [cond]
Relational Operator used
eq Equal to
nc Not equal to
gtGreater than
gc Greater than or equal to
lt Less than
lc Less than or equal to
Unix/sh/14
Test - String Comparison
String tests used by test
n str True, if str not a null string
z str True, if str is a null string
S1 = S2 True, if S1 = S2
S1! = S2 True, if S1 S2
str True, if str is assigned and not null
Logical Operators
a .AND.
O .OR.
! Not
e.g. If [! -f fname]
then
echo “file does not exists”
fi
Unix/sh/15
The Case Statement
Format :
case <expression> in
<pattern 1> ) <execute commands> ;;
<pattern 2> ) <execute commands> ;;
<…>
<…>
esac
Unix/sh/16
The Case Statement
E.g.
E.g.
Case “$ans” in
[yY] [eE] [sS] ;;
[nN] [oO] exit ;;
*) “invalid option” ;;
Unix/sh/17
While Statement
Format :
while <condition is true>
do
<execute statements>
done
Unix/sh/18
While Statement
E.g. Script to edit, compile & execute a program
while true
do
cc $1
case $? In
o) echo “Compilation Successful”
echo “Executing a.out”
a.out ; exit ;;
Unix/sh/19
Break & Continue Statement
Continue : Suspends execution of all statements
following it, and switches control to
top of loop for next iteration
Break : causes control to break out of the loop
Unix/sh/20
Until Statement
Complement of while stm
loop body is executed repeatedly as long as the condition remains
false
Unix/sh/21
for Statement
Format :
for variable in list
do
<execute commands>
done
e.g. for x in 1 2 3
do
echo “The value of x is $x”
done
e.g.for var in $PATH $HOME $MAIL
do
echo “$var”
done
e.g.for file in *.c
do
cc $file
done
Unix/sh/22