SlideShare a Scribd company logo
Version no
Unix Shell Scripting
2
Table of Contents
• Module 1 Getting started 3
• Module 2 General Purpose Utilities 11
• Module 3 Working with Directories & Files 21
• Module 4 The Shell 44
• Module 5 vi Editor 52
• Module 6 File permissions 70
• Module 7 File Comparison 77
• Module 8 The process 81
• Module 9 Filters 91
• Module 10 Advanced Filters 108
• Module 11 Introduction to shell scripting 131
• Module 12 User inputs and expressions 147
• Module 13 Conditions and loop 158
• Module 14 Some more scripts 178
• Module 15 Communication Utilities 187
• Module 16 System Administration 191
3
Module 1. Getting started
• Overview
 What is UNIX
 Features of Unix
 Evolution of Unix
 Flavors of Unix
 Unix architecture
 Signing into Unix
 Unix commands
4
What is UNIX?
• What is UNIX?
UNiplexed Information and Computing System
5
Features of Unix
Features
• Multi-user
• Multi-tasking
• Hierarchical directory structure
• Portability
Drawback
• Lack of GUI
• Difficult operating system to learn
 Worded commands & messages
 Many UNIX commands have short names
6
Evolution of Unix
Developed by : Dennis Ritchie and Ken Thompson
Where : Bell Telephone Laboratories
When : 1969
7
Flavors of Unix
• Solaris (Sun Microsystem)
• HP-UX (Hewlett Packard UniX)
• AIX (Advanced Interactive eXecutive ) by IBM
• Most popular is Linux which is very strong in network and
internet features.
8
Unix Architecture
Applications/ Commands
Shell
Kernel
Hardware
9
Signing onto Unix
• Every user of a UNIX system must log on to the computer
using an existing account.
• Login name is to be entered at login prompt.
login: user1
Password:
$
10
Unix Commands  
• Unix commands are entered at command prompt ($)
$ ls
• All unix commands must be entered in lowercase.
• Between command name and its options, there must always
be a space.
$ ls -l
• To cancel the entire command before u press Enter, use Del
key.
11
Module 2. General Purpose Utilities
• Overview
 banner
 cal
 date
 Who
 echo
 passwd
 bc
 script
12
banner : display message in poster form
$ banner hello
$ banner Hello Unix
$ banner “Hello Unix”
13
cal : calendar
$ cal
$ cal 7 2008
$ cal 1752
14
date: Display System date
$ date
$ date +%a
$ date +%A
$ date +%b
$ date +%B
$ date +%d
$ date +%D
15
who : Login details
$ who
$ who –H
$ who am i
16
echo : Display Messages
$ echo Welcome To Unix
$ echo Welcome To Unix
17
passwd: change password
$ passwd
18
bc :calculator
$ bc
12+5
17
12*12; 2^3
144
8
<ctrl-d>
$
19
script: Record your session
$ script
Script started, file is typescript
$ _
$ exit
Script done, file is typescript
20
Few other commands
1. clear
2. tty
3. uname
4. logname
5. exit
21
Module 3 . Working with Directories & Files
• Overview
 Unix File Structure & its features
 Types of Files
 Rules for filenames
 Directory Handling Commands
pwd, mkdir, cd, rmdir
 File Handling Commands
cat, ls, cp,mv,rm, ln, wc
 Absolute path & Relative path
 Setting alias
 Inode
22
Unix File Structure
• Unix treats everything it knows and understands as a file.
• Unix File system resembles an upside down tree.
/ (root)
bin lib dev usr tmp etc mnt
user1 user2 bin
23
Features of Unix file Structure
• It has a hierarchical file structure
• Files can grow dynamically
• Files have access permissions
• All devices are implemented as files.
24
Types of Files
• Unix files are categorized into :
- Ordinary Files
- Directory files
- Device files
25
Rules for filenames
• Filename can consist of:
• Alphabets and numerals
• Period (.), hyphen (-) and underscore (_)
• Filename can consist of upto 255 characters.
• Files may or may not have extensions
26
Sample Tree structure
projects/
reports/ graphs/
g_jan g_feb
backups/
backup/
backup
r_jan r_feb r_mar b_jan b_feb
27
pwd command : Present working directory
$ pwd
$ pwd
28
mkdir command : Make directory
$ mkdir projects
$ mkdir graphs backup
$ mkdir –p projects/graphs
$ mkdir –m 700 reports
$ mkdir [option] [directory_name]
29
cd command : Change Directory
$ cd graphs
$ cd projects/reports
$ cd ..
$ cd
$ cd [directory_name]
30
rmdir command : Remove Directory
$ rmdir graphs
$ rmdir reports graphs backups
$ rmdir backups/backup
$ rmdir –p backups/backup
$ rmdir [options] [directory_name]
31
cat command: create new file
Creates file with the specified name and can add data into it.
$ cat > r_jan
This is report of January month.
<ctrl+d>
$ cat r_jan
$ cat file1 file2 > r_jan
$ cat file1 file2 >> r_jan
32
The cat command (Contd…)
Displays the contents of the file with numbering
$ cat –n [file_name]
Display $ at end of each line
$ cat –e [file_name]
33
ls command : listing files & directories
$ ls [option] [directory/file]
Options to ls
-a displays hidden files also
-l long listing if files showing 7 attributes of a file
-i displays inode number
-r Reverse order while sorting
-s Print size of each file, in blocks
-t Sort by modification time
-F Marks executables with * and directories with /
-R Recursive listing of all files in sub-directories
-d List directory entries
34
The ls command (Contd…)
Examples:
$ ls
$ ls d*
$ ls [dk]*
$ ls d?
$ ls -l
$ ls -F
$ ls -i
$ ls -r –t or ls -rt
$ ls -a
35
Absolute path and Relative path
• Absolute path
• Relative path
36
File & directory related commands (Contd..)
/
home/
training/
projects/
reports/
graphs/
backups/
backup/
backup
g_jan g_feb
r_jan
r_feb
r_mar
b_jan
b_feb
37
The cp command
Options to cp:
-i : Prompt before overwrite
-r : Recursive copying
Examples:
$ cp r_jan reports
$ cp -i r_jan reports
$ cp [option] [source] [destination]
38
mv command: Renaming & moving files
Options to mv:
-i : Prompt before overwrite
Examples:
$ mv b_jan newfile
$ mv file1 file2 newdir
$ mv olddir newdir
$ mv -i b_jan newfile
$ mv b_jan newdir
$ mv b_jan newdir/
$ mv [option] [source] [destination]
39
The rm command
Options to rm:
-i : Confirm before removing
-r : Recursive deletion
-f : Forceful deletion
Examples:
$ rm r_jan
$ rm -i r_feb
$ rm -f r_mar
$ rm –r backups
$ rm [option] [file/directory]
40
Setting alias for commands
$ alias
$ alias rm='rm -i'
$ alias cls=clear
$ unalias cls
$ unalias -a
41
Count words using wc
Options to wc:
-l : Display no. of lines
-w : Display no. of words
-c : Display no. of characters
Examples:
$ wc new_link
3 12 59 new_link
$ wc -l new_link
3 new_link
$ wc [option] [file_name]
42
File links
Soft link or symbolic link or symlink
$ ln -s [source_path] [destination_path]
Hard link
$ ln [source_path] [destination_path]
43
Inode
Inode contains
 File type (executable, block special etc)
 Permissions (read, write etc)
 Owner
 Group
 File Size
 File access, change and modification time
 File deletion time
 Number of links (soft/hard)
 Extended attribute such as append only or no one can delete file
including root user (immutability)
44
Module 4. Shell
• Overview
 What is Shell
 Unix shells
 Redirection
 System Variables
 .profile file
45
What is shell?
Different shells
(Various Unix
Commands)
Kernel
Hardware
46
Unix shells
• Bourne shell (sh)
• C shell (csh)
• Korn Shell (ksh)
47
Redirection
1. Standard input (<)
$ wc < emp.lst
1. Standard output (>)
$ ls > listing
$ cat >> file_name
1. Standard error (2>)
$ cat emplist 2>errorlogfile
48
Connecting Commands with Pipes
$ who > emp.lst
$ wc –l emp.lst
$ who | wc –l
$ ls | wc –l >fcount
49
tee command
$ who | tee users.list
$ who | tee users.list |wc –l
$ who | tee /dev/tty | wc -l
50
Unix System variables
System variables Purpose
PATH The set of directories the the shell will search
in the order given, to find the command
HOME Set of users home directories
MAIL The directory in which electronic mail is sent
to you is places
PS1 The primary prompt string
PS2 The secondary prompt string
SHELL It sets the path name of the shell interpreter
TERM Identifies the kind of terminal you are using
LOGNAME Displays the username
51
.profile
• This file is present in home your directory.
• It contains the script to be executed during login time.
52
Module 5 . The vi editor
• Overview
 Introduction to vi editor
 Moving between 3 modes of vi editor
 Input Mode commands
 Navigation
 Moving between the lines and scrolling pages
 Ex mode commands
 Delete text
 Replacing and changing text
 Yanking, pasting and joining line
 Pattern search and replace
 Customizing vi
 Abbreviating text
 Multiple file editing in vi
53
Introduction to vi
• vi( short for visual editor) is an editor available with all
versions of unix.
• It allows user to view and edit the entire document at same
time.
• Written by Bill Joy
• Its case-sensitive
54
How to Invoke vi session
$ vi newfile
$ vi
55Three modes of vi editor
Input
Mode
Command
Mode
ex
Mode
<Esc>
i, I, o, O, r, R, s, S, a, A
<Esc> : <Enter>
56
Input Mode Commads
Input text
i Inserts text to left of cursor
I Inserts text at the beginning of the line
Append text
a Appends text to right of cursor
A Appends text at the end of the line
Opening a new line
o Opens line below the cursor
O Opens line above the cursor
57
Input Commands (contd.)
Replacing text
r ch Replaces single character under cursor with ‘ch’
R Replaces text from cursor to right
s Replaces single character under cursor with any
number of characters
S Replaces entire line
58
Navigation
h
h l
j
k
59
Moving between the lines and scrolling pages
Moving between the lines
G Goes to end of the file
nG Goes to line number ‘n’
Scrolling page
ctrl+f Scrolls page forward
ctrl+b Scrolls page backward
ctrl+d Scrolls half page forward
ctrl+u Scrolls half page backward
60
Ex mode commands: Save file and quit
Saving & Quitting
:w Saves the files & remains in the editing mode
:wq Saves & quits from editing mode
:x Saves & quits from editing mode
:q! Quitting the editing mode without saving any
changes
Writes selected lines into specified file_name
:w <file_name> Save file as file_name
:n1,n2w <file_name> Writes lines n1 to n2 to specified
file_name
:.w <file_name> Writes current line into specified file
:$w <file_name> Writes last line into specified file
name
61
Commands for Deleting text
x Deletes a single character
dw Deletes a word ( or part of the word)
dd Deletes the entire line
db Deletes the word to previous start of the word
d0 Deletes current line from cursor to beginning of line
d$ Deletes current line from cursor till end of line
nx Deletes n characters
ndw Deletes n words
ndd Deletes n lines
62
Yanking, pasting and joining line
Yanking/Copying text
yw Yanks word from cursor position
yy Yanks current line
y0 Yanks current line from cursor to beginning of line
y$ Yanks current line from cursor till end of line
nyy Yank the specified number of lines
Paste
p Pastes text
Join
J Joins following lines with current one
63
Pattern search
Command Purpose
/pattern Searches forward for pattern
?pattern Searches backward for pattern
n Repeats the last search command
N Repeats search in opposite direction
64
Building Patterns for searching
Character Meaning
* Zero or more characters
[ ] Set or range of characters
^ Matches pattern towards beginning of line
$ Matches pattern towards end of line
< Forces match to occur only at beginning of word
> Forces match to occur at end of word
Examples:
^finance
finance$
[a-d]ing
team>
Wing*
[^p]art
65
Search and Replace
Command Purpose
:s/str1/str2 Replaces first occurrence of str1 with str2
:s/str1/str2/g Replaces all occurrences of str1 with str2
:m,n s/str1/str2 /g
Replaces all occurrence of str1 with str2 from
lines m to n
:.,$ s/str1/str2/g
Replaces all occurrence of str1 with str2 from
current line to end of file
Example:
:s/director/member/g
66
Customizing vi
:set number/set nu Sets display of line numbers ON
:set nonumber/set nonu Set no number
:set wrapmargin=20 Set wrap margin equal to 20
:set ignorecase Ignorecase while searching
:set ai Set auto indent
:set showmode Shows the working mode
:set autowrite Automatically writes when moves
to another page
67
Abbreviating text
Command Purpose
:abbr <abbr> <longform> an abbreviation is defined for longform
:abbr lists currently defined abbreviation
:una <abbr> Unabbreviates the abbreviation
Example:
:abbr pspl pragati software pvt. ltd.
68
.exrc file
$ vi .exrc
set nu
set ignorecase
set showmode
set wrapmargin=60
69
Multiple file editing in vi
Command Purpose
vi file1 file2 Loads both files in vi for editing.
:n Permits editing of next file
:n! Permits editing of next file without saving current file
:rew Permits editing of first file in buffer
:rew! Permits editing of first file without saving current file
:args Displays names of all files in buffer
:f Displays name of current file
Example:
$ vi file1 file2 file3
$ vi *.c
70
Module 6 . File permissions
• Overview
 Permission for file and directories
 The chmod command
 Octal notation
 umask (default file and directory permission)
71
Permissions for files and directories
Three types of permissions
1. Read
For files : cat, vi
For directories : ls
1. Write
For files : cat > file_name, vi
For directories : mkdir, rmdir, mc
1. Execute
For files : ./filename
For directories : cd
72
The chmod command
Category
u : user
g : group
o : others
a : all
Operation
+ : assign
- : revoke
= : absolute
Attributes
r : read
w: write
x : execute
$chmod [category] [operation] [attributes] [file/directory]
73
Example of chmod
Giving user execution permission
$ chmod u+x report.txt
$ ls –l report.txt
-rwxrw-r-- 1 user1 group1 320 Jun 26 23:26 report.txt
For others remove read permissions
$ chmod o-r report.txt
$ ls -l report.txt
-rwxrw---- 1 user1 group1 320 Jun 26 23:26 report.txt
Give absolute permissions to group as read and execute
$ chmod g=rx report.txt
$ ls -l report.txt
-rwxr-x--- 1 user1 group1 320 Jun 26 23:26 report.txt
74
Octal notation
Permissions OctalNotation
4 Read
2 Write
1 Execute
$ chmod [octal_notation] [file/directory]
75
Example of chmod using octal notations
Original permissions
$ ls-l report.txt
-rwxr-x--- 1 user1 group1 320 Jun 26 23:26 report.txt
Assigning permissions using octal notations
$ chmod 664 report.txt
After assigning permissions
$ ls -l report.txt
-rw-rw-r-- 1 user1 group1 320 Jun 26 23:26 report.txt
76
umask (default file and directory permissions)
Default umask
$ umask
0002
Default file permissions
$ touch report.txt
$ ls -l report.txt
-rw-rw-r-- 1 user1 group1 320 Jun 26 23:41 report.txt
Change umask
$ umask 066
File permissions with umask changed
$ touch newReport.txt
$ ls -l newReport.txt
-rw------- 1 user1 group1 320 Jun 26 23:42 newReport.txt
77
Module 7 . File comparision
• Overview
Comparing files using cmp command
Comparing files using comm command
Comparing files using diff command
78
Comparing files using cmp command
$ cmp [file1] [file2]
$ cat file1
CDROM
CPU
FLOPPY DISK
HARD DISK
KEYBOARD
MONITOR
PRINTER
$ cat file2
CDROM
CPU
HARD DISK
KEYBOARD
MONITOR
MOUSE
PRINTER
$ cmp file1 file2
file1 file2 differ: byte 13, line 3
79
comm command : finding what is common
$ comm [file1] [file2]
Output for comm command is
$ comm file1 file2
CDROM
CPU
FLOPPY DISK
HARD DISK
KEYBOARD
MONITOR
MOUSE
PRINTER
80
diff command: convert one file into another
$ diff [file1] [file2]
$ diff file1 file2
3d2
< FLOPPY DISK
6a6
> MOUSE
81
Module 8 . The process
• Overview
 Process status – ps
 Mechanism of process creation
 Executing jobs in background
 Job control
 kill command
 Scheduling jobs for later execution
82
ps : Process status
Options to ps:
-a : Display all user processes
-f : Display Process ancestry
-u : Display process of a user
-e : Display system processes
Example:
$ps
PID TTY TIME CMD
1032 pts/1 00:00:00 ksh
1074 pts/1 00:00:00 ps
$ps –a
$ ps [options]
83
Process status – ps (Contd…)
$ ps -u user1
$ ps -f
UID PID PPID C STIME TTY TIME CMD
user1 1032 1031 0 09:10:02 pts/1 00:00 bash
user1 1275 1032 0 09:10:02 pts/1 00:00 ps –f
84
Mechanism of Process Creation
• Three phases are involved in creation of process :
• fork
• exec
• wait
85
Executing jobs in background
In order to execute a process in background, just terminate
the command line with ‘&’
$ sort –o emp.lst emp.lst &
550 # job’s PID
86
nohup : Log Out Safely
• nohup ( no hangup) command, when prefixed to a command,
permits execution of the process even after user has logged
out.
$ nohup sort emp.last &
87
Job Control
Commands used for job control:
bg, fg, kill, jobs
$cat > test
this is example of suspended process
[1]+ Stopped cat >test
$ jobs
[1]+ Stopped cat >test
$ bg %cat
cat >test &
$ fg %cat
continued
88
kill command: Terminate a process
$ kill 1346
$ kill 1346 121 400
$ kill -9 1346
$ kill $! # kills last background job
89
Scheduling jobs for later Execution
at command
$ at 15:15
echo “Hello” > /dev/tty
<ctrl+d>
Options:
– l ( list ) : View list of submitted jobs
-r (remove ) : Remove submitted job
90
Scheduling jobs using cron
cron lets you schedule jobs so that they can run repeatedly.
$ crontab -l
00-10 17 * * * echo “Hello” > /dev/tty
day of week (0 - 6) (Sunday=0)
month (1 - 12)
day of month (1 - 31)
hour (0 - 23)
min (0 - 59)
91
Module 9 . Filters
• Overview
pr
head
tail
cut
paste
sort
uniq
tr
grep
egrep
fgrep
92
Data file
$cat -n emp.lst
10 | A.K.Sharma | Director | Production | 12/Mar/1950 | 70000
11 | Sumit Singh | D.G.M | Marketing | 19/Apr/1943 | 60000
12 | Barun Sen | Director | Personnel | 11/May/1947 | 78000
23 | Bipin Das | Secretary | Personnel | 11/Jul/1947 | 40000
50 | N.k.Gupta | Chairman | Admin | 30/Aug/1956 | 64000
43 | Chanchal | Director | Sales | 03/Sep/1938 | 67000
93
pr : Paginating files
Options to pr:
-d Double spaces input.
-n displays line numbers.
-o n offset lines by ‘n’ spaces
-h Displays header as specified instead of file name.
Example:
$pr emp.lst
$pr -dn emp.lst
$pr –h "Employee Details" emp.lst
$ pr [option] [file_name]
94
head: Displaying the beginning of a file
Options to head:
-n Displays specified numbers of lines
Example:
$ head emp.lst
$ head -n 6 emp.lst | nl
$ head [option] [file_name]
95
tail : Displaying the end of the file
Options to tail:
-n Displays specified numbers of lines
Example:
$ tail emp.lst
$ tail -6 emp.lst
$tail +10 emp.lst
$ tail [option] [file_name]
96
cut : Slitting a file vertically
Options to cut:
-c : cutting columns
-f : cutting fields
-d : specify delimeter
Example:
$ cut -c 1-4 emp.lst
$ cut -d "|" -f1 emp.lst
$ cut -d "|" -f2,4 emp.lst
$ cut [option] [file_name]
97
paste : Pasting files
Options :
-d specify delimeter for pasting files
Example:
$ paste empno empname
$ paste -d “:" empno empname
$ paste [option] [file_name]
98
sort : Ordering a file
Options:
-n sorts numerically
-r Reverses sort order
-c Check whether file is sorted
+k Starts sorting after skipping kth
field
-k Stops sorting after kth
field
-o File Write result to “File” instead of standard output
-t Specify field separator
$ sort [option] [file_name]
99
sort : Ordering a file (Contd..)
Example:
$ sort emp.lst
$ sort -t "|" -k2 emp.lst
$ sort -t "|" -k2 emp1.lst -o emp1.lst
$sort -t"|" -k 3,3 -k 2,2 emp.lst
100
uniq : Locate repeated and no repeated lines
Options:
-d : selects only one copy of the repeated lines
-c : displays the frequency of occurrence of all lines
-u : selects only non-repeated lines
Examples:
$ cut -d"|" -f 4 emp1.lst > departments
$ sort departments | uniq
$ sort departments | uniq -d
$ sort departments | uniq -c
$ uniq [file_name]
101
tr : translating characters
$tr '|/' '~~' < emp.lst
Changing case for text
$tr [a-z] [A-Z] < emp.lst
Deleting characters
$tr -d '|/' < emp.lst
$ tr [options] [expression1] [expression2] [standard_input]
102
grep : Searching for pattern
Simple search
$grep “sales” emp.lst
$grep d.g.m. emp.lst
$grep 'jai sharma' emp.lst
Ignoring case
$grep -i "SALES" emp.lst
$ grep [options] [file_name(s)]
103
grep : Searching for pattern (Contd…)
Deleting specified pattern lines
$grep -v "sales" emp.lst
Displaying line numbers
$grep -n "sales" emp.lst
Counting lines containing pattern
$grep -c sales emp.lst
Displaying filenames
$grep -l sales *
104
Regular Expressions
Symbols Significance
* Matches zero or more occurrence of previous
character
. Matches a single character
[pqr] Matches a single character p, q or r
[a-r] Matches a single character within range a – r
[^pqr] Matches a single character which is not p, q or r
^pattern Matches pattern at beginning of line
pattern$ Matches pattern at end of line
<pattern Matches pattern at beginning of word
pattern> Matches pattern at end of word
105
grep : Searching for pattern (Contd…)
Searches for a pattern only at the beginning of a word and not
anywhere on the line
$grep "<man" emp.lst
Searches for a pattern only at the end of a word and not
anywhere on the line
$grep "man>" emp.lst
Using metacharacters
$grep sa[kx]s*ena emp.lst
$grep ag[agr][ra]r*wal emp.lst
106
egrep : Extended grep
$grep -e sengupta -e dasgupta -e gupta emp.lst
$egrep "sengupta|dasgupta|gupta" emp.lst
$egrep "(sen|das|)gupta" emp.lst
107
fgrep : Fixed string grep
Taking patterns from a File
$cat -n pattern.lst
1 sales
2 gupta
$fgrep -f pattern.lst emp.lst
108
Module 10 : Advanced Filters – sed and awk
• Overview
 sed- stream editor
 Introduction to awk
 Formatting output with printf
 Logical and relational operators
 Number processing
 The -f option
 The BEGIN and END section
 Positional parameters and shell variables
 Built-in variables
 Making awk interactive using 'getline' statements
 Arrays
 Functions
 The if statement
 Looping constructs
109
sed: Stream EDitor
• sed is a multi-purpose tool which combines work of several
filters.
• Designed by Lee McMohan.
• It is used for performing non-interactive applications
110
sed instruction
Line addressing
Print 3rd
line
$head -n 3 emp.lst | tail -n 1
$sed '3p' emp.lst
Print only 3rd
line
$sed -n '3p' emp.lst
Print only last line
$sed -n '$p' emp.lst
$ sed [options] ‘address action’ [file_name]
111
Using multiple instructions ( -e )
Print 3rd
and 6th
line
$sed -n -e'3p' -e'6p' emp.lst
Print 3rd
to 6th
line
$sed -n -e '3,6p' emp.lst
112
Context addressing
$ sed -n '/gupta/p' emp.lst
$ sed -n -e'/gupta/p' -e'/sharma/p' emp.lst
$ sed -n -e'/gupta/,/sharma/p' emp.lst
$ sed -n '/ag[agr][ar]r*wal/p' emp.lst
113
Writing selected lines to a file
$sed -n '/director/w dlist' emp.lst
$sed -n '/dirctor/w dlist
> /manager/w mlist
> /executive/w elist' emp.lst
114Text editing
$sed '$i
1000|jitesh sharma' emp.lst
$sed '$a
1000|jitesh sharma' emp.lst
$sed '/director/d' emp.lst
115
Substitution
$ sed 's/ | / : /' emp.lst
$ sed 's/ | / : /g' emp.lst
$ sed '1,5s/ | / : /g' emp.lst
[address]s/string1/string2/flag
116
Introduction to awk
• Authors : Aho, Weinberger , Kernighnan
• Use : Pattern scanning and processing language
• Unlike other filters, awk operates at field level
117
awk
$ awk '/director/ { print }' emp.lst
$ awk –F"|" '/sales/ {print $2,$3,$4,$6}' emp.lst
$ awk –F “|” ‘NR==3, NR==6 {print NR, $2, $3, $6 }’ emp.lst
$ awk <options> ‘ address {action}’ <file(s)>
118
Formatting output with printf
$ awk -F "|" ‘/director/ {
printf("%3d %-20s %-12s %dn", NR, $2, $3, $6)
}' emp.lst
119
The logical and relational operators
Logical And &&
Logical Or ||
$ awk -F "|" '$3=="director" || $3=="chairman" { print }' emp.lst
$ awk -F "|" '$6 > 7500 { print }' emp.lst
120
Number processing
$ awk -F "|" '$3=="director" {
printf “%d %d n", $6, $6*0.15
}' emp.lst
$ awk -F "|" '$3=="director" && $6>6700{
kount++
printf "%d %s n", kount, $2
}' emp.lst
121
The –f option
$ cat empawk.awk
$3=="director"||$6>7500 {printf"%-20s %-12s %d n", $2,$3,$6 }
$ awk -F"|" -f empawk.awk emp.lst
122
The BEGIN and the END sections
$ cat -n empawk2.awk
1 BEGIN {
2 printf "nttEmployee abstractnn"
3 }
4 $6 > 7500 {
5 kount++; tot += $6
6 printf "%3d %-20s %-12s %dn", kount, $2, $3, $6
7 }
8 END {
9 printf "nttThe average basic pay is %6dn", tot/kount
10 }
$ awk –F”|” –f empawk2.awk emp.lst
123
Positional parameters and shell variables
$ $6 > 7500
$ awk –F”|” –f empawk2.awk mpay=7800 emp.lst
(change empawk2.awk line number 4 as $5>mpay )
124
Built-in variables
$ awk 'BEGIN { FS="|" ; OFS="~"}
> $5~/5[25]$/ {print $1,$2,$3,$5}' emp.lst
$ awk 'BEGIN {FS="|" }
> NF!=6 {
> print "Record No ", NR, " has", NF, " fields"}' emp.lst
$ awk '$6>6000
> { print FILENAME, $0 }' emp.lst
125
Making awk interactive using getline statement
$ cat -n empawk3.awk
1 BEGIN {
2 printf "nEnter the cut-off basic pay : "
3 getline var < "/dev/tty"
4 printf "nttEmployee abstractnn"
5 }
6 $6 > var {
7 printf( "%3d %-20s %-12s %d n", ++kount, $2, $3, $6)
8 }
$ awk –F”|” –f empawk3.awk emp.lst
126
Arrays
$ cat -n empawk4.awk
1 BEGIN { FS = "|"
2 printf ("n%46sn", "Basic Da Hra Gross" )
3 }
4 /sales|marketing/ {
5 da = 0.25 * $6; hra = 0.50 * $6;
6 gp = $6+hra+da;
7 tot[1] +=$6 ; tot[2] += da;
8 tot[3] +=hra; tot[4] += gp
9 kount++
10 }
11 END {
12 printf "nt Average %5d %5d %5d %5dn", 
13 tot[1]/kount, tot[2]/kount, tot[3]/kount, tot[4]/kount
14 }
127
Functions
$ awk '{ print length()}' emp.lst
$ awk 'BEGIN{ print sqrt(144)}‘
$ awk 'BEGIN{ print int(100.987)}'
$ awk 'BEGIN{ print system("date")}'
$ awk 'BEGIN{ print system("clear")}‘
$ awk 'BEGIN{ print index("pragati software","gati")}‘
128
The if statement
if ($6 < 6000)
{
hra = 0.50 * $6
da = 0.25 * $6
}
else
{
hra=0.40*$6
da=1000
}
129
Looping with for
$ awk -F"|" '{
> kount[$3]++}
> END{
> for(design in kount)
> print(kount[design],design)
> }' emp.lst
130
Looping with while
$ cat -n newline.awk
BEGIN{
FS="|"
}
{ newline("-",50);
printf("%d %s", $1, $2);
}
function newline(ch, num){
printf "n";
i=1
while(i<num){
printf("%c",ch);
i++;
}
printf("n");
}
$ awk -f newline.awk emp.lst
131
Module 11 . Introduction to shell scripting
• Overview
 Why shell scripting?
 When not to use shell scripting?
 Shell as an interpreter
 Writing your first shell script (first.sh)
 Different ways to execute a shell script
 The sha bang statement
 Some basics of scritping
 The export statement
 Comments in shell script
132
Why shell scripting?
• Automating commonly used commands
• Performing system administration and trouble shooting
• Creating simple application
133
When not to use shell scripts?
1. Resource intensive task when speed is a factor
2. Heavy math operations
3. Portability
4. Structured programming
5. Subcomponents with interlocking dependencies.
6. Extensive file operations
7. Multi dimensional arrays
8. Data structures like linked lists or trees
9. Generate or manipulate graphics or GUIs.
10. Direct access to system hardware.
11. Socket programming
12. Libraries to interface with legacy code
13. Proprietary or closed source software
134
Shell as an interpreter
Compilers i.e., C/C++ Interpreter i.e., Shell
Windows Unix
Prg1.c Prg1.c
Prg1.obj Prg1.o
Prg1.exe Prg1.out
Prg1Prg1
Compilation
Linking
Renaming
Prg1.sh
Prg1
Interpretation
Renaming
135
Writing your first shell script (first.sh)
$ echo "Hello World of UNIX shell scripts….“
136
Different ways to execute a shell script
1. shell_name scriptName
2. scriptName
3. ./scriptName
4. /FQPN/scriptName
5. . ./FQPN/scriptName
* FQPN – Full Qualified Path Name, e.g., /home/redhat/scripts/
137
shell_name scriptName
Run this script by using any of the following commands
$ bash scriptName
$ ksh scriptName
$ csh scriptName
138
scriptName
To run the script like a command
1) Set the path in PATH variable
2) Set execute permission for the script
Run this script by using the following command
$ scriptName
139
./scriptName
This method can be used for that particular directory
Requires execution permission
Run this script by using the following command
$ ./scriptName
outbox inbox
scripts
first.sh
first.sh first.sh
140
/FQPN/scriptName
This method of running the script requires execution permission
It bypasses the PATH
Run this script by using the following command
$ /FQPN/scriptName
$ /home/scripts/first.sh
homeetc
/
first.sh
scripts
141
. ./FQPN/scriptName
This method of running the script does not requires execution
permission
This method bypasses the PATH. It honors PATH user
specifies.
Run this script by using the following command
$ . ./FQPN/scriptName
142
The sha bang statement
• Specifies which kind of interpreter should get followed
#!/bin/bash
#!/bin/ksh
#!/bin/csh
#!/bin/more
#!/bin/rm
143
magicScript.sh
1. #!/bin/rm
2. echo “executing this script”
144
The export statement
1. echo $$
2. A=10
3. echo $A
4. ksh
5. echo $$
6. echo $A
7. exit
8. export A
9. ksh
10. echo $A
11. A=90
12. echo $A
13. exit
14. echo $A
15. export –n A
145
first.sh (contd…)
1. #!/bin/bash
2. echo "Hello world of UNIX Shell Script"
3. echo "process id of your shell is: $$“
4. echo “value of A is $A”
5. A=500
6. echo “value of A is $A”
146
Comments in shell scripts
1. #!/bin/bash
2. # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
3. # Pragati Software Private Limited
4. # Purpose : This is first shell script.
5. # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
6. echo "Hello world of UNIX Shell Script"
7. echo "process id of your shell is: $$“
8. echo “value of A is $A”
9. A=500
10. echo “value of A is $A”
147
Module 12 . User inputs and expressions
• Overview
 Using read
 Command line arguments
 Special parameters used by the shell
 Using set
 Using shift
 exit and exit status of the commands
 Computations : expr
 Various quotes on shell prompt
 Arithmetic operations using 'let'
148
Using read
$ cat -n search.sh
echo -e "Enter filename : c"
read filename
echo -e "Enter pattern :c"
read pattern
grep $pattern $filename
149
Command line arguments
$ cat -n searchPattern.sh
echo "Program : $0"
echo "Number of arguments specified is $#"
echo "The arguments are $*"
grep $1 $2
150
Creating USAGE messages
$ cat -n usageDemo.sh
if [ $# -ne 2 ] ; then
echo "USAGE : addnum.sh <num1> <num2>"
else
echo "Addition is : `expr $1 + $2`"
fi
151
Special parameters used by the shell
Shell parameters Significance
$1,$2,… Positional parameters representing command
line argument
$# Number of arguments specified in command
line
$0 Name of executed command
$* Complete set of positional parameters as a
single string
$@ Each quoted string treated as separate
argument
$? Exit status of last command
$$ PID of current shell
$! PID of the last background job
152
Using set
• “set” assigns its positional parameters to the positional
parameters
$ set 123 456 789
$ echo “$1 is $1 ,$2 is $2 ,$3 is $3”
153
Using shift
$ cat -n shiftDemo.sh
1 #!/bin/ksh
2 NO_ARGS=$#
3 echo .Number of arguments passed $NO_ARGS.
4 echo "Argument 1 is $1"
5 echo "Argument 2 is $2"
6 echo "Argument 3 is $3"
7 echo "Argument 4 is $4"
8 echo "Argument 5 is $5"
9 echo "Argument 6 is $6"
10 echo "Argument 7 is $7"
11 echo "Argument 8 is $8"
12 echo "Argument 9 is $9"
13 shift 2
14 echo "Argument 10 is $8"
15 echo "Argument 10 is $9"
154
exit and exit status of command
• exit
• echo $?
155
Computations : expr
$ cat -n compute.sh
#!/bin/ksh
A=500
B=20
echo "Two values are $A and $B"
ADD=`expr $A + $B`
#ADD=$((A+B))
echo "Addition is $ADD"
SUB=`expr $A - $B`
echo "Subtraction is $SUB"
MULT=`expr $A * $B`
echo "Multiplication is $MULT"
DIV=`expr $A / $B`
echo "Addition is $DIV"
156
Various quotes on shell prompt
• "" (double quotes)
• '' (single quotes)
• `` (grave accent, back or reverse quotes)
157
Arithmetic operations using ‘let’
$ let sum=A+B
$ echo $sum
$ let mult=$A*$B
$ echo $mult
158
Module 13 . Conditions and loops
• Overview
 Logical operators ( && and || )
 The if condition
 Using 'test' and '[ ]' to evaluate expression
 String comparison operator
 File comparison operator
 The case statement
 The while loop
 The until loop
 The for loop
 The break statement
 The continue statement
159
Logical operators ( && and || )
$ grep ‘director’ emp.lst && echo “Pattern found”
$ grep ‘managet’ emp.lst || echo “Pattern not found”
160
The if condition
1. if [ condition is true ] ; then
statements
fi
1. if [ condition is true ] ; then
statements
else
statements
fi
1. if [ condition is true ] ; then
statements
elif [ condition is true ] ; then
statements
else
statements
fi
161
ifSearch.sh
$ cat -n ifSerach.sh
1 #!/bin/ksh
2 echo -e "Enter filename : c" ; read filename
3 echo -e "Enter pattern :c" ; read pattern
4 grep $pattern $filename
5 GREP_STATUS=$?
6 if [ $GREP_STATUS -eq 1 ] ; then
7 echo "Pattern not found"
8 fi
9 if [ $GREP_STATUS -eq 2 ] ; then
10 echo "File not found"
11 fi
162
Using ‘test’ and ‘[ ]’ to evaluate expressions
$ x=5;y=7;z=7.2
$ test $x –eq $y ; echo $?
$ test $x –lt $y ; echo $?
$ test $z –gt $y ; echo $?
$ test $z –eq $y ; echo $?
Shorthand for test
$ [ $z –eq $y ] ; echo $?
163
String comparison operators
Operators Meaning
s1=s2 String s1=s2
s1!=s2 String s1 is not equal to s2
-n str String str is not a null String
-z str String str is a null String
str String str is a assigned and null String
s1= =s2 String s1= =s2(korn and bash only)
164
File comparison operators
Operators Meaning
-f file File exist and is a regular file
-r file File exist and is readable
-w file File exist and is writable
-e file File exist and is executable
-d file File exist and is directory
-e file File exist (korn and bash only)
-L file File exist and is a symbolic link
165
fileSearch.sh
$ cat -n fileSearch.sh
1 echo -e "Enter file namec" ; read filename
2 if [ -e $filename ] ; then
3 echo "Enter pattern" ; read pattern
4 grep $pattern $filename
5 GREP_STATUS=$?
6 if [ $GREP_STATUS -eq 1 ] ; then
7 echo "Pattern not found."
8 fi
9 else
10 echo "File not found."
11 fi
166
elifTest.sh
$ cat -n elifTest.sh
1 A=500
2 B=20
3 echo "Two values are $A and $B"
4 echo -e "Enter your choice n 1)Additionn2)Subtractionn3)Multiplication
n4)Divisionn"
5 read CH
6 if [ $CH -eq 1 ] ; then
7 echo "Addition is `expr $A + $B`"
8 elif [ $CH -eq 2 ] ; then
9 echo "Subtraction is `expr $A - $B`"
10 elif [ $CH -eq 3 ] ; then
11 echo "Multiplication is `expr $A * $B`"
12 elif [ $CH -eq 4 ] ; then
13 echo "Division is `expr $A / $B`"
14 fi
167
The case statement
case condition in
1)statements
;;
----
----
*)statements
;;
esac
168
case test
$ cat -n caseTest.sh
1 A=500
2 B=20
3 echo "Two values are $A and $B"
4 echo -e "Enter your choice n
1)Additionn2)Subtractionn3)Multiplication n4)Divisionn"
5 read CH
6 case "$CH" in
7 1) echo "Addition is `expr $A + $B`" ;;
8 2) echo "Subtraction is `expr $A - $B`" ;;
9 3) echo "Multiplication is `expr $A * $B`" ;;
10 4) echo "Division is `expr $A / $B`" ;;
11 *) echo "Invalid option"
12 esac
169
Matching multiple patterns
$ cat -n multimatch.sh
1 echo "Do you wish to continue [y/n]"
2 read ch
3 case "$ch" in
4 y|Y)
5 echo " $ch is selected"
6 ;;
7 n|N)
8 echo " $ch is selected"
9 ;;
10 esac
170
The while loop
Syntax :-
while condition is true
do
commands
done
171
whileDemo.sh
1 #!/bin/ksh
2 PATTERN_NOT_FOUND=10
3 FILE_NOT_FOUND=20
4 ch='y'
5 while [ $ch = 'y' -o $ch = 'Y' ]
6 do
7 echo -e "Enter filename : c" ; read filename
8 echo -e "Enter pattern :c" ; read pattern
9 grep $pattern $filename 2>/dev/null
10 GREP_STATUS=$?
11 if [ $GREP_STATUS -eq 1 ] ; then
12 echo "Pattern not found...."
13 fi
14 if [ $GREP_STATUS -eq 2 ]; then
15 echo "File not found..."
16 fi
17 echo "Do you want to continue [y/n]?" ; read ch
18 done
172
The until loop
Syntax :-
until condition is true
do
commands
done
173
untilDemo.sh
$ cat -n untilDemo.sh
1 #!/bin/bash
2 until [ $var == end ]
3 do
4 echo "Input variable #1 "
5 echo "(end to exit)"
6 read var1
7 echo "variable #1 = $var1"
8 done
174
The for loop
Syntax :
for variable in list
do
commands
done
175
forDemo.sh
1. for planet in Mercury Mars Saturn
do
echo $planet
done
1. PLANETS=“Mercury Mars Saturn “
for planet in $PLANETS
do
echo $planet
done
1. for((i=0;i<5;i++))
do
echo $i
done
176
breakDemo.sh
$ cat -n breakDemo.sh
1 LIMIT=10
2 a=0
3 while [ "$a" -le "$LIMIT" ]
4 do
5 a=$((a+1))
6 if [ "$a" -gt 5 ];then
7 break # Skip entire rest of loop.
8 fi
9 echo -n "$a "
10 done
177
continueDemo.sh
$ cat -n continueDemo.sh
1 LIMIT=20 # Upper limit
2 echo "Printing even numbers from 1 to 20 "
3 a=0
4 while [ $a -le "$LIMIT" ]
5 do
6 let a=a+1
7 REM=`expr $a % 2`
8 if [ $REM -ne 0 ]
9 then
10 continue # Skip rest of this particular loop iteration.
11 fi
12 echo "$a"
13 done
178
Module 14 . Some more scripts
• Overview
 Block redirection
 Block commenting
 Arrays
 Functions
179
Block redirection (output to file)
$ cat -n blockRedirectionDemo.sh
1 #!/bin/ksh
2 i=1
3 while [ $i -lt 10 ]
4 do
5 echo $i
6 let i=i+1
7 done>outfile.sh
8 if [ -f outfile.sh ]
9 then
10 echo "File exit"
11 else
12 echo "File does not exits"
13 fi
180
Block redirection (input from file)
$ cat -n readFile.sh
1 while read line
2 do
3 echo $line
4 done<emp.lst
181
Block commenting
$ cat -n blockComment.sh
1 echo "Block comment"
2 <<BLOCKCOMMENT
3 Hi Hello
4 this I can not see
5 BLOCKCOMMENT
6 echo "End of Comment"
182
Arrays
$ cat -n arrayDemo.sh
1 #!/bin/bash
2 arr[0]=zero
3 arr[1]=one
4 arr[2]=two
5 arr[3]=three
6 arr[4]=four
7 echo ${arr[0]}
8 echo ${arr[1]}
9 echo ${arr[2]}
10 echo ${arr[3]}
11 echo ${arr[4]}
183
Declare variable as array
$ cat -n declare_array.sh
1 #!/bin/bash
2 declare -a arr
3 for((i=0;i<10;i++))
4 do
5 arr[$i]=$i
6 done
7 for((i=0;i<10;i++))
8 do
9 echo ${arr[$i]}
10 done
184
Functions
function-name ( ) {
command1
command2
.....
...
commandN
}
185
Simple function
$ cat -n calc.sh
1 add(){
2 echo "Enter num1:"
3 read num1
4 echo "Enter num2:"
5 read num2
6 echo "Addtion is `expr $num1 + $num2`"
7 }
8 add
186
Passing parameters to the function
$ cat -n parameterPassing.sh
1 add(){
2 num1=$1
3 num2=$2
4
5 echo "Addition is `expr $num1 + $num2`"
6 }
7
8 add 10 30
187
Module 15. Communication utilities
• Overview
 The write and wall command
 Controlling messages using mesg
 Sending mails
188
The write and wall command
$ wall
Hi all
ctrl+d
$ wall < file
$ write redhat
Hi redhat
ctrl+d
189
Controlling messages using mesg
$ tty
/dev/tty1
$ mesg < /dev/tty2
is y
$ mesg n < /dev/tty2
$ mesg < /dev/tty2
is n
$ mesg
is y
190
Sending mails
$ mail training@pragatisoftware.com
Subject: Hi This is just a short note to say hello.
I don't have anything else right now. .
Cc:
ctrl+d
$ mail
191
Module 16. System Administration
• Overview
 root : super user’s login
 Administrator privileges
 Starting up and shutting down the system
 Disk management
 find command
 Backups
 File compression
 User administration
 File system administraton
192
root : Super user’s login
login: root
password:
#
Prompt of root is #
193
su : Acquiring super user status
$ su
Password:*****<enter>
# pwd
/home/local #prompt changes, but directory doesn’t
194
Administrator’s privileges
# passwd
# date
195
Starting Up the System
1. Kernel is Loaded
2. Kernel then starts spawning further processes, most
important is init ( PID =1).
3. init spawns further processes. init becomes parent of all
shells.
4. Unix system can be set up in number of modes( Run-levels)
that are controlled by init.
• Single-user mode
• Multi-user Mode
196
Shutting Down the system
# shutdown -g2
# shutdown -g0
# shutdown -g0 –i6
197
Managing Disk Space
Disk free space
# df
Disk Usage
# du
198
find : Locating Files
# find / -name newfile.sh –print
# find . –mtime -2 -print
find path_list selection_criteria action
199
Expressions used by find
Selection Criteria Significance
-name flname Selects file flname
-user uname Selects file if owned by ‘uname’
-type f Selects file if it is an ordinary file
-type d
Selects file if it is a directory
-group gname
Selects file if owned by group ‘gname’
-atime +x Selects file if access time is > x days
-mtime +x Selects file if modification time is > x days
-newer flname Selects file if modified after ‘flname’
200
Expressions used by find (contd..)
Action Significance
-exec cmd {} ; Executes Unix command cmd
-ok cmd {} ; Executes Unix command cmd, after user
confirmation
-print Prints selected file on standard output
201
Backing up files using tar
Creating tar file
$ tar -cvf backup.tar *
Extracting tar file
$ tar -xvf backup.tar
202
Compression and decompression of files
zip and unzip
zip newFile.zip filename
unzip newFile.zip
gzip and gunzip
gzip filename
gunzip filename
203
User Administration
• For user management, Unix Provides following command:
 useradd
 usermod
 userdel
# useradd –u 210 –g dba –c “RDBMS” –d “/home/oracle” –s
/bin/ksh”
–m oracle
# usermod –s /bin/csh oracle
# userdel oracle
204
File System Administration
fsck : File System Checking
# fsck /dev/user1
Ad

Recommended

Conhecendo o Windows Server 2012
Conhecendo o Windows Server 2012
Eduardo Sena
 
Oracle SQL, PL/SQL best practices
Oracle SQL, PL/SQL best practices
Smitha Padmanabhan
 
Weblogic
Weblogic
sudeeporcl
 
Db2 tutorial
Db2 tutorial
The Vision and Insight Corner
 
VMware HCI solutions - 2020-01-16
VMware HCI solutions - 2020-01-16
David Pasek
 
Using API Platform to build ticketing system #symfonycon
Using API Platform to build ticketing system #symfonycon
Antonio Peric-Mazar
 
Db2 Important questions to read
Db2 Important questions to read
Prasanth Dusi
 
IBM Cloud PowerVS - AIX and IBM i on Cloud
IBM Cloud PowerVS - AIX and IBM i on Cloud
Nagesh Ramamoorthy
 
FHIR Server 安裝與使用
FHIR Server 安裝與使用
Lorex L. Yang
 
MS-SQL SERVER ARCHITECTURE
MS-SQL SERVER ARCHITECTURE
Douglas Bernardini
 
Elastic Search Indexing Internals
Elastic Search Indexing Internals
Gaurav Kukal
 
Server side programming
Server side programming
javed ahmed
 
Skillwise-IMS DB
Skillwise-IMS DB
Skillwise Group
 
Overview of Rest Service and ASP.NET WEB API
Overview of Rest Service and ASP.NET WEB API
Pankaj Bajaj
 
2 1計數原理
2 1計數原理
leohonesty0814
 
[오픈소스컨설팅]클라우드기반U2L마이그레이션 전략 및 고려사항
[오픈소스컨설팅]클라우드기반U2L마이그레이션 전략 및 고려사항
Ji-Woong Choi
 
Configuring Domino To Be An Ldap Directory And To Use An Ldap Directory
Configuring Domino To Be An Ldap Directory And To Use An Ldap Directory
Edson Oliveira
 
Storage overview
Storage overview
Christalin Nelson
 
第一讲:虚拟语气
第一讲:虚拟语气
luciashun
 
WebLogic 12c & WebLogic Mgmt Pack
WebLogic 12c & WebLogic Mgmt Pack
DLT Solutions
 
Los sistemas operativos prof j romero
Los sistemas operativos prof j romero
romeprofe
 
Nginx
Nginx
Dhrubaji Mandal ♛
 
Java web services using JAX-WS
Java web services using JAX-WS
IndicThreads
 
Witsml data processing with kafka and spark streaming
Witsml data processing with kafka and spark streaming
Mark Kerzner
 
Ultimate Free SQL Server Toolkit
Ultimate Free SQL Server Toolkit
Kevin Kline
 
Windows Server 2019.pptx
Windows Server 2019.pptx
masbulosoke
 
Dmv's & Performance Monitor in SQL Server
Dmv's & Performance Monitor in SQL Server
Zeba Ansari
 
WebLogic Deployment Plan Example
WebLogic Deployment Plan Example
James Bayer
 
Operating System Laboratory presentation .ppt
Operating System Laboratory presentation .ppt
PDhivyabharathi2
 
Unix and Linux - The simple introduction
Unix and Linux - The simple introduction
Amity University Noida
 

More Related Content

What's hot (20)

FHIR Server 安裝與使用
FHIR Server 安裝與使用
Lorex L. Yang
 
MS-SQL SERVER ARCHITECTURE
MS-SQL SERVER ARCHITECTURE
Douglas Bernardini
 
Elastic Search Indexing Internals
Elastic Search Indexing Internals
Gaurav Kukal
 
Server side programming
Server side programming
javed ahmed
 
Skillwise-IMS DB
Skillwise-IMS DB
Skillwise Group
 
Overview of Rest Service and ASP.NET WEB API
Overview of Rest Service and ASP.NET WEB API
Pankaj Bajaj
 
2 1計數原理
2 1計數原理
leohonesty0814
 
[오픈소스컨설팅]클라우드기반U2L마이그레이션 전략 및 고려사항
[오픈소스컨설팅]클라우드기반U2L마이그레이션 전략 및 고려사항
Ji-Woong Choi
 
Configuring Domino To Be An Ldap Directory And To Use An Ldap Directory
Configuring Domino To Be An Ldap Directory And To Use An Ldap Directory
Edson Oliveira
 
Storage overview
Storage overview
Christalin Nelson
 
第一讲:虚拟语气
第一讲:虚拟语气
luciashun
 
WebLogic 12c & WebLogic Mgmt Pack
WebLogic 12c & WebLogic Mgmt Pack
DLT Solutions
 
Los sistemas operativos prof j romero
Los sistemas operativos prof j romero
romeprofe
 
Nginx
Nginx
Dhrubaji Mandal ♛
 
Java web services using JAX-WS
Java web services using JAX-WS
IndicThreads
 
Witsml data processing with kafka and spark streaming
Witsml data processing with kafka and spark streaming
Mark Kerzner
 
Ultimate Free SQL Server Toolkit
Ultimate Free SQL Server Toolkit
Kevin Kline
 
Windows Server 2019.pptx
Windows Server 2019.pptx
masbulosoke
 
Dmv's & Performance Monitor in SQL Server
Dmv's & Performance Monitor in SQL Server
Zeba Ansari
 
WebLogic Deployment Plan Example
WebLogic Deployment Plan Example
James Bayer
 
FHIR Server 安裝與使用
FHIR Server 安裝與使用
Lorex L. Yang
 
Elastic Search Indexing Internals
Elastic Search Indexing Internals
Gaurav Kukal
 
Server side programming
Server side programming
javed ahmed
 
Overview of Rest Service and ASP.NET WEB API
Overview of Rest Service and ASP.NET WEB API
Pankaj Bajaj
 
[오픈소스컨설팅]클라우드기반U2L마이그레이션 전략 및 고려사항
[오픈소스컨설팅]클라우드기반U2L마이그레이션 전략 및 고려사항
Ji-Woong Choi
 
Configuring Domino To Be An Ldap Directory And To Use An Ldap Directory
Configuring Domino To Be An Ldap Directory And To Use An Ldap Directory
Edson Oliveira
 
第一讲:虚拟语气
第一讲:虚拟语气
luciashun
 
WebLogic 12c & WebLogic Mgmt Pack
WebLogic 12c & WebLogic Mgmt Pack
DLT Solutions
 
Los sistemas operativos prof j romero
Los sistemas operativos prof j romero
romeprofe
 
Java web services using JAX-WS
Java web services using JAX-WS
IndicThreads
 
Witsml data processing with kafka and spark streaming
Witsml data processing with kafka and spark streaming
Mark Kerzner
 
Ultimate Free SQL Server Toolkit
Ultimate Free SQL Server Toolkit
Kevin Kline
 
Windows Server 2019.pptx
Windows Server 2019.pptx
masbulosoke
 
Dmv's & Performance Monitor in SQL Server
Dmv's & Performance Monitor in SQL Server
Zeba Ansari
 
WebLogic Deployment Plan Example
WebLogic Deployment Plan Example
James Bayer
 

Similar to Unix fundamentals and_shell scripting (20)

Operating System Laboratory presentation .ppt
Operating System Laboratory presentation .ppt
PDhivyabharathi2
 
Unix and Linux - The simple introduction
Unix and Linux - The simple introduction
Amity University Noida
 
Unix Shell Script - 2 Days Session.pptx
Unix Shell Script - 2 Days Session.pptx
Rajesh Kumar
 
Unix environment [autosaved]
Unix environment [autosaved]
Er Mittinpreet Singh
 
Shell_Scripting.ppt
Shell_Scripting.ppt
KiranMantri
 
Linux powerpoint
Linux powerpoint
bijanshr
 
Unix tutorial-08
Unix tutorial-08
Tushar Jain
 
Commands and shell programming (3)
Commands and shell programming (3)
christ university
 
Unix tutorial-08
Unix tutorial-08
kavitha_tala
 
58518522 study-aix
58518522 study-aix
homeworkping3
 
Chapter 2 unix system commands
Chapter 2 unix system commands
LukasJohnny
 
PowerPoint_merge.ppt on unix programming
PowerPoint_merge.ppt on unix programming
Priyadarshini648418
 
Module 02 Using Linux Command Shell
Module 02 Using Linux Command Shell
Tushar B Kute
 
Unix ppt
Unix ppt
Dr Rajiv Srivastava
 
Unix OS & Commands
Unix OS & Commands
Mohit Belwal
 
Unix
Unix
Sudharsan S
 
Karkha unix shell scritping
Karkha unix shell scritping
chockit88
 
basic-unix.pdf
basic-unix.pdf
OmprakashNath2
 
Unix
Unix
Sudharsan S
 
Linux Administration
Linux Administration
harirxg
 
Operating System Laboratory presentation .ppt
Operating System Laboratory presentation .ppt
PDhivyabharathi2
 
Unix and Linux - The simple introduction
Unix and Linux - The simple introduction
Amity University Noida
 
Unix Shell Script - 2 Days Session.pptx
Unix Shell Script - 2 Days Session.pptx
Rajesh Kumar
 
Shell_Scripting.ppt
Shell_Scripting.ppt
KiranMantri
 
Linux powerpoint
Linux powerpoint
bijanshr
 
Unix tutorial-08
Unix tutorial-08
Tushar Jain
 
Commands and shell programming (3)
Commands and shell programming (3)
christ university
 
Chapter 2 unix system commands
Chapter 2 unix system commands
LukasJohnny
 
PowerPoint_merge.ppt on unix programming
PowerPoint_merge.ppt on unix programming
Priyadarshini648418
 
Module 02 Using Linux Command Shell
Module 02 Using Linux Command Shell
Tushar B Kute
 
Unix OS & Commands
Unix OS & Commands
Mohit Belwal
 
Karkha unix shell scritping
Karkha unix shell scritping
chockit88
 
Linux Administration
Linux Administration
harirxg
 
Ad

Recently uploaded (20)

Battle of Bookworms 2025 - U25 Literature Quiz by Pragya
Battle of Bookworms 2025 - U25 Literature Quiz by Pragya
Pragya - UEM Kolkata Quiz Club
 
Introduction to Generative AI and Copilot.pdf
Introduction to Generative AI and Copilot.pdf
TechSoup
 
Publishing Your Memoir with Brooke Warner
Publishing Your Memoir with Brooke Warner
Brooke Warner
 
Sustainable Innovation with Immersive Learning
Sustainable Innovation with Immersive Learning
Leonel Morgado
 
Non-Communicable Diseases and National Health Programs – Unit 10 | B.Sc Nursi...
Non-Communicable Diseases and National Health Programs – Unit 10 | B.Sc Nursi...
RAKESH SAJJAN
 
Wax Moon, Richmond, VA. Terrence McPherson
Wax Moon, Richmond, VA. Terrence McPherson
TerrenceMcPherson1
 
Paper 107 | From Watchdog to Lapdog: Ishiguro’s Fiction and the Rise of “Godi...
Paper 107 | From Watchdog to Lapdog: Ishiguro’s Fiction and the Rise of “Godi...
Rajdeep Bavaliya
 
PEST OF WHEAT SORGHUM BAJRA and MINOR MILLETS.pptx
PEST OF WHEAT SORGHUM BAJRA and MINOR MILLETS.pptx
Arshad Shaikh
 
BINARY files CSV files JSON files with example.pptx
BINARY files CSV files JSON files with example.pptx
Ramakrishna Reddy Bijjam
 
Capitol Doctoral Presentation -June 2025.pptx
Capitol Doctoral Presentation -June 2025.pptx
CapitolTechU
 
“THE BEST CLASS IN SCHOOL”. _
“THE BEST CLASS IN SCHOOL”. _
Colégio Santa Teresinha
 
Paper 108 | Thoreau’s Influence on Gandhi: The Evolution of Civil Disobedience
Paper 108 | Thoreau’s Influence on Gandhi: The Evolution of Civil Disobedience
Rajdeep Bavaliya
 
Assisting Individuals and Families to Promote and Maintain Health – Unit 7 | ...
Assisting Individuals and Families to Promote and Maintain Health – Unit 7 | ...
RAKESH SAJJAN
 
The Man In The Back – Exceptional Delaware.pdf
The Man In The Back – Exceptional Delaware.pdf
dennisongomezk
 
What are the benefits that dance brings?
What are the benefits that dance brings?
memi27
 
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
ChristinaFortunova
 
Ray Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big Cycle
Dadang Solihin
 
SPENT QUIZ NQL JR FEST 5.0 BY SOURAV.pptx
SPENT QUIZ NQL JR FEST 5.0 BY SOURAV.pptx
Sourav Kr Podder
 
Chalukyas of Gujrat, Solanki Dynasty NEP.pptx
Chalukyas of Gujrat, Solanki Dynasty NEP.pptx
Dr. Ravi Shankar Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
How to Create an Event in Odoo 18 - Odoo 18 Slides
How to Create an Event in Odoo 18 - Odoo 18 Slides
Celine George
 
Battle of Bookworms 2025 - U25 Literature Quiz by Pragya
Battle of Bookworms 2025 - U25 Literature Quiz by Pragya
Pragya - UEM Kolkata Quiz Club
 
Introduction to Generative AI and Copilot.pdf
Introduction to Generative AI and Copilot.pdf
TechSoup
 
Publishing Your Memoir with Brooke Warner
Publishing Your Memoir with Brooke Warner
Brooke Warner
 
Sustainable Innovation with Immersive Learning
Sustainable Innovation with Immersive Learning
Leonel Morgado
 
Non-Communicable Diseases and National Health Programs – Unit 10 | B.Sc Nursi...
Non-Communicable Diseases and National Health Programs – Unit 10 | B.Sc Nursi...
RAKESH SAJJAN
 
Wax Moon, Richmond, VA. Terrence McPherson
Wax Moon, Richmond, VA. Terrence McPherson
TerrenceMcPherson1
 
Paper 107 | From Watchdog to Lapdog: Ishiguro’s Fiction and the Rise of “Godi...
Paper 107 | From Watchdog to Lapdog: Ishiguro’s Fiction and the Rise of “Godi...
Rajdeep Bavaliya
 
PEST OF WHEAT SORGHUM BAJRA and MINOR MILLETS.pptx
PEST OF WHEAT SORGHUM BAJRA and MINOR MILLETS.pptx
Arshad Shaikh
 
BINARY files CSV files JSON files with example.pptx
BINARY files CSV files JSON files with example.pptx
Ramakrishna Reddy Bijjam
 
Capitol Doctoral Presentation -June 2025.pptx
Capitol Doctoral Presentation -June 2025.pptx
CapitolTechU
 
Paper 108 | Thoreau’s Influence on Gandhi: The Evolution of Civil Disobedience
Paper 108 | Thoreau’s Influence on Gandhi: The Evolution of Civil Disobedience
Rajdeep Bavaliya
 
Assisting Individuals and Families to Promote and Maintain Health – Unit 7 | ...
Assisting Individuals and Families to Promote and Maintain Health – Unit 7 | ...
RAKESH SAJJAN
 
The Man In The Back – Exceptional Delaware.pdf
The Man In The Back – Exceptional Delaware.pdf
dennisongomezk
 
What are the benefits that dance brings?
What are the benefits that dance brings?
memi27
 
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
ChristinaFortunova
 
Ray Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big Cycle
Dadang Solihin
 
SPENT QUIZ NQL JR FEST 5.0 BY SOURAV.pptx
SPENT QUIZ NQL JR FEST 5.0 BY SOURAV.pptx
Sourav Kr Podder
 
How to Create an Event in Odoo 18 - Odoo 18 Slides
How to Create an Event in Odoo 18 - Odoo 18 Slides
Celine George
 
Ad

Unix fundamentals and_shell scripting

  • 2. 2 Table of Contents • Module 1 Getting started 3 • Module 2 General Purpose Utilities 11 • Module 3 Working with Directories & Files 21 • Module 4 The Shell 44 • Module 5 vi Editor 52 • Module 6 File permissions 70 • Module 7 File Comparison 77 • Module 8 The process 81 • Module 9 Filters 91 • Module 10 Advanced Filters 108 • Module 11 Introduction to shell scripting 131 • Module 12 User inputs and expressions 147 • Module 13 Conditions and loop 158 • Module 14 Some more scripts 178 • Module 15 Communication Utilities 187 • Module 16 System Administration 191
  • 3. 3 Module 1. Getting started • Overview  What is UNIX  Features of Unix  Evolution of Unix  Flavors of Unix  Unix architecture  Signing into Unix  Unix commands
  • 4. 4 What is UNIX? • What is UNIX? UNiplexed Information and Computing System
  • 5. 5 Features of Unix Features • Multi-user • Multi-tasking • Hierarchical directory structure • Portability Drawback • Lack of GUI • Difficult operating system to learn  Worded commands & messages  Many UNIX commands have short names
  • 6. 6 Evolution of Unix Developed by : Dennis Ritchie and Ken Thompson Where : Bell Telephone Laboratories When : 1969
  • 7. 7 Flavors of Unix • Solaris (Sun Microsystem) • HP-UX (Hewlett Packard UniX) • AIX (Advanced Interactive eXecutive ) by IBM • Most popular is Linux which is very strong in network and internet features.
  • 9. 9 Signing onto Unix • Every user of a UNIX system must log on to the computer using an existing account. • Login name is to be entered at login prompt. login: user1 Password: $
  • 10. 10 Unix Commands   • Unix commands are entered at command prompt ($) $ ls • All unix commands must be entered in lowercase. • Between command name and its options, there must always be a space. $ ls -l • To cancel the entire command before u press Enter, use Del key.
  • 11. 11 Module 2. General Purpose Utilities • Overview  banner  cal  date  Who  echo  passwd  bc  script
  • 12. 12 banner : display message in poster form $ banner hello $ banner Hello Unix $ banner “Hello Unix”
  • 13. 13 cal : calendar $ cal $ cal 7 2008 $ cal 1752
  • 14. 14 date: Display System date $ date $ date +%a $ date +%A $ date +%b $ date +%B $ date +%d $ date +%D
  • 15. 15 who : Login details $ who $ who –H $ who am i
  • 16. 16 echo : Display Messages $ echo Welcome To Unix $ echo Welcome To Unix
  • 19. 19 script: Record your session $ script Script started, file is typescript $ _ $ exit Script done, file is typescript
  • 20. 20 Few other commands 1. clear 2. tty 3. uname 4. logname 5. exit
  • 21. 21 Module 3 . Working with Directories & Files • Overview  Unix File Structure & its features  Types of Files  Rules for filenames  Directory Handling Commands pwd, mkdir, cd, rmdir  File Handling Commands cat, ls, cp,mv,rm, ln, wc  Absolute path & Relative path  Setting alias  Inode
  • 22. 22 Unix File Structure • Unix treats everything it knows and understands as a file. • Unix File system resembles an upside down tree. / (root) bin lib dev usr tmp etc mnt user1 user2 bin
  • 23. 23 Features of Unix file Structure • It has a hierarchical file structure • Files can grow dynamically • Files have access permissions • All devices are implemented as files.
  • 24. 24 Types of Files • Unix files are categorized into : - Ordinary Files - Directory files - Device files
  • 25. 25 Rules for filenames • Filename can consist of: • Alphabets and numerals • Period (.), hyphen (-) and underscore (_) • Filename can consist of upto 255 characters. • Files may or may not have extensions
  • 26. 26 Sample Tree structure projects/ reports/ graphs/ g_jan g_feb backups/ backup/ backup r_jan r_feb r_mar b_jan b_feb
  • 27. 27 pwd command : Present working directory $ pwd $ pwd
  • 28. 28 mkdir command : Make directory $ mkdir projects $ mkdir graphs backup $ mkdir –p projects/graphs $ mkdir –m 700 reports $ mkdir [option] [directory_name]
  • 29. 29 cd command : Change Directory $ cd graphs $ cd projects/reports $ cd .. $ cd $ cd [directory_name]
  • 30. 30 rmdir command : Remove Directory $ rmdir graphs $ rmdir reports graphs backups $ rmdir backups/backup $ rmdir –p backups/backup $ rmdir [options] [directory_name]
  • 31. 31 cat command: create new file Creates file with the specified name and can add data into it. $ cat > r_jan This is report of January month. <ctrl+d> $ cat r_jan $ cat file1 file2 > r_jan $ cat file1 file2 >> r_jan
  • 32. 32 The cat command (Contd…) Displays the contents of the file with numbering $ cat –n [file_name] Display $ at end of each line $ cat –e [file_name]
  • 33. 33 ls command : listing files & directories $ ls [option] [directory/file] Options to ls -a displays hidden files also -l long listing if files showing 7 attributes of a file -i displays inode number -r Reverse order while sorting -s Print size of each file, in blocks -t Sort by modification time -F Marks executables with * and directories with / -R Recursive listing of all files in sub-directories -d List directory entries
  • 34. 34 The ls command (Contd…) Examples: $ ls $ ls d* $ ls [dk]* $ ls d? $ ls -l $ ls -F $ ls -i $ ls -r –t or ls -rt $ ls -a
  • 35. 35 Absolute path and Relative path • Absolute path • Relative path
  • 36. 36 File & directory related commands (Contd..) / home/ training/ projects/ reports/ graphs/ backups/ backup/ backup g_jan g_feb r_jan r_feb r_mar b_jan b_feb
  • 37. 37 The cp command Options to cp: -i : Prompt before overwrite -r : Recursive copying Examples: $ cp r_jan reports $ cp -i r_jan reports $ cp [option] [source] [destination]
  • 38. 38 mv command: Renaming & moving files Options to mv: -i : Prompt before overwrite Examples: $ mv b_jan newfile $ mv file1 file2 newdir $ mv olddir newdir $ mv -i b_jan newfile $ mv b_jan newdir $ mv b_jan newdir/ $ mv [option] [source] [destination]
  • 39. 39 The rm command Options to rm: -i : Confirm before removing -r : Recursive deletion -f : Forceful deletion Examples: $ rm r_jan $ rm -i r_feb $ rm -f r_mar $ rm –r backups $ rm [option] [file/directory]
  • 40. 40 Setting alias for commands $ alias $ alias rm='rm -i' $ alias cls=clear $ unalias cls $ unalias -a
  • 41. 41 Count words using wc Options to wc: -l : Display no. of lines -w : Display no. of words -c : Display no. of characters Examples: $ wc new_link 3 12 59 new_link $ wc -l new_link 3 new_link $ wc [option] [file_name]
  • 42. 42 File links Soft link or symbolic link or symlink $ ln -s [source_path] [destination_path] Hard link $ ln [source_path] [destination_path]
  • 43. 43 Inode Inode contains  File type (executable, block special etc)  Permissions (read, write etc)  Owner  Group  File Size  File access, change and modification time  File deletion time  Number of links (soft/hard)  Extended attribute such as append only or no one can delete file including root user (immutability)
  • 44. 44 Module 4. Shell • Overview  What is Shell  Unix shells  Redirection  System Variables  .profile file
  • 45. 45 What is shell? Different shells (Various Unix Commands) Kernel Hardware
  • 46. 46 Unix shells • Bourne shell (sh) • C shell (csh) • Korn Shell (ksh)
  • 47. 47 Redirection 1. Standard input (<) $ wc < emp.lst 1. Standard output (>) $ ls > listing $ cat >> file_name 1. Standard error (2>) $ cat emplist 2>errorlogfile
  • 48. 48 Connecting Commands with Pipes $ who > emp.lst $ wc –l emp.lst $ who | wc –l $ ls | wc –l >fcount
  • 49. 49 tee command $ who | tee users.list $ who | tee users.list |wc –l $ who | tee /dev/tty | wc -l
  • 50. 50 Unix System variables System variables Purpose PATH The set of directories the the shell will search in the order given, to find the command HOME Set of users home directories MAIL The directory in which electronic mail is sent to you is places PS1 The primary prompt string PS2 The secondary prompt string SHELL It sets the path name of the shell interpreter TERM Identifies the kind of terminal you are using LOGNAME Displays the username
  • 51. 51 .profile • This file is present in home your directory. • It contains the script to be executed during login time.
  • 52. 52 Module 5 . The vi editor • Overview  Introduction to vi editor  Moving between 3 modes of vi editor  Input Mode commands  Navigation  Moving between the lines and scrolling pages  Ex mode commands  Delete text  Replacing and changing text  Yanking, pasting and joining line  Pattern search and replace  Customizing vi  Abbreviating text  Multiple file editing in vi
  • 53. 53 Introduction to vi • vi( short for visual editor) is an editor available with all versions of unix. • It allows user to view and edit the entire document at same time. • Written by Bill Joy • Its case-sensitive
  • 54. 54 How to Invoke vi session $ vi newfile $ vi
  • 55. 55Three modes of vi editor Input Mode Command Mode ex Mode <Esc> i, I, o, O, r, R, s, S, a, A <Esc> : <Enter>
  • 56. 56 Input Mode Commads Input text i Inserts text to left of cursor I Inserts text at the beginning of the line Append text a Appends text to right of cursor A Appends text at the end of the line Opening a new line o Opens line below the cursor O Opens line above the cursor
  • 57. 57 Input Commands (contd.) Replacing text r ch Replaces single character under cursor with ‘ch’ R Replaces text from cursor to right s Replaces single character under cursor with any number of characters S Replaces entire line
  • 59. 59 Moving between the lines and scrolling pages Moving between the lines G Goes to end of the file nG Goes to line number ‘n’ Scrolling page ctrl+f Scrolls page forward ctrl+b Scrolls page backward ctrl+d Scrolls half page forward ctrl+u Scrolls half page backward
  • 60. 60 Ex mode commands: Save file and quit Saving & Quitting :w Saves the files & remains in the editing mode :wq Saves & quits from editing mode :x Saves & quits from editing mode :q! Quitting the editing mode without saving any changes Writes selected lines into specified file_name :w <file_name> Save file as file_name :n1,n2w <file_name> Writes lines n1 to n2 to specified file_name :.w <file_name> Writes current line into specified file :$w <file_name> Writes last line into specified file name
  • 61. 61 Commands for Deleting text x Deletes a single character dw Deletes a word ( or part of the word) dd Deletes the entire line db Deletes the word to previous start of the word d0 Deletes current line from cursor to beginning of line d$ Deletes current line from cursor till end of line nx Deletes n characters ndw Deletes n words ndd Deletes n lines
  • 62. 62 Yanking, pasting and joining line Yanking/Copying text yw Yanks word from cursor position yy Yanks current line y0 Yanks current line from cursor to beginning of line y$ Yanks current line from cursor till end of line nyy Yank the specified number of lines Paste p Pastes text Join J Joins following lines with current one
  • 63. 63 Pattern search Command Purpose /pattern Searches forward for pattern ?pattern Searches backward for pattern n Repeats the last search command N Repeats search in opposite direction
  • 64. 64 Building Patterns for searching Character Meaning * Zero or more characters [ ] Set or range of characters ^ Matches pattern towards beginning of line $ Matches pattern towards end of line < Forces match to occur only at beginning of word > Forces match to occur at end of word Examples: ^finance finance$ [a-d]ing team> Wing* [^p]art
  • 65. 65 Search and Replace Command Purpose :s/str1/str2 Replaces first occurrence of str1 with str2 :s/str1/str2/g Replaces all occurrences of str1 with str2 :m,n s/str1/str2 /g Replaces all occurrence of str1 with str2 from lines m to n :.,$ s/str1/str2/g Replaces all occurrence of str1 with str2 from current line to end of file Example: :s/director/member/g
  • 66. 66 Customizing vi :set number/set nu Sets display of line numbers ON :set nonumber/set nonu Set no number :set wrapmargin=20 Set wrap margin equal to 20 :set ignorecase Ignorecase while searching :set ai Set auto indent :set showmode Shows the working mode :set autowrite Automatically writes when moves to another page
  • 67. 67 Abbreviating text Command Purpose :abbr <abbr> <longform> an abbreviation is defined for longform :abbr lists currently defined abbreviation :una <abbr> Unabbreviates the abbreviation Example: :abbr pspl pragati software pvt. ltd.
  • 68. 68 .exrc file $ vi .exrc set nu set ignorecase set showmode set wrapmargin=60
  • 69. 69 Multiple file editing in vi Command Purpose vi file1 file2 Loads both files in vi for editing. :n Permits editing of next file :n! Permits editing of next file without saving current file :rew Permits editing of first file in buffer :rew! Permits editing of first file without saving current file :args Displays names of all files in buffer :f Displays name of current file Example: $ vi file1 file2 file3 $ vi *.c
  • 70. 70 Module 6 . File permissions • Overview  Permission for file and directories  The chmod command  Octal notation  umask (default file and directory permission)
  • 71. 71 Permissions for files and directories Three types of permissions 1. Read For files : cat, vi For directories : ls 1. Write For files : cat > file_name, vi For directories : mkdir, rmdir, mc 1. Execute For files : ./filename For directories : cd
  • 72. 72 The chmod command Category u : user g : group o : others a : all Operation + : assign - : revoke = : absolute Attributes r : read w: write x : execute $chmod [category] [operation] [attributes] [file/directory]
  • 73. 73 Example of chmod Giving user execution permission $ chmod u+x report.txt $ ls –l report.txt -rwxrw-r-- 1 user1 group1 320 Jun 26 23:26 report.txt For others remove read permissions $ chmod o-r report.txt $ ls -l report.txt -rwxrw---- 1 user1 group1 320 Jun 26 23:26 report.txt Give absolute permissions to group as read and execute $ chmod g=rx report.txt $ ls -l report.txt -rwxr-x--- 1 user1 group1 320 Jun 26 23:26 report.txt
  • 74. 74 Octal notation Permissions OctalNotation 4 Read 2 Write 1 Execute $ chmod [octal_notation] [file/directory]
  • 75. 75 Example of chmod using octal notations Original permissions $ ls-l report.txt -rwxr-x--- 1 user1 group1 320 Jun 26 23:26 report.txt Assigning permissions using octal notations $ chmod 664 report.txt After assigning permissions $ ls -l report.txt -rw-rw-r-- 1 user1 group1 320 Jun 26 23:26 report.txt
  • 76. 76 umask (default file and directory permissions) Default umask $ umask 0002 Default file permissions $ touch report.txt $ ls -l report.txt -rw-rw-r-- 1 user1 group1 320 Jun 26 23:41 report.txt Change umask $ umask 066 File permissions with umask changed $ touch newReport.txt $ ls -l newReport.txt -rw------- 1 user1 group1 320 Jun 26 23:42 newReport.txt
  • 77. 77 Module 7 . File comparision • Overview Comparing files using cmp command Comparing files using comm command Comparing files using diff command
  • 78. 78 Comparing files using cmp command $ cmp [file1] [file2] $ cat file1 CDROM CPU FLOPPY DISK HARD DISK KEYBOARD MONITOR PRINTER $ cat file2 CDROM CPU HARD DISK KEYBOARD MONITOR MOUSE PRINTER $ cmp file1 file2 file1 file2 differ: byte 13, line 3
  • 79. 79 comm command : finding what is common $ comm [file1] [file2] Output for comm command is $ comm file1 file2 CDROM CPU FLOPPY DISK HARD DISK KEYBOARD MONITOR MOUSE PRINTER
  • 80. 80 diff command: convert one file into another $ diff [file1] [file2] $ diff file1 file2 3d2 < FLOPPY DISK 6a6 > MOUSE
  • 81. 81 Module 8 . The process • Overview  Process status – ps  Mechanism of process creation  Executing jobs in background  Job control  kill command  Scheduling jobs for later execution
  • 82. 82 ps : Process status Options to ps: -a : Display all user processes -f : Display Process ancestry -u : Display process of a user -e : Display system processes Example: $ps PID TTY TIME CMD 1032 pts/1 00:00:00 ksh 1074 pts/1 00:00:00 ps $ps –a $ ps [options]
  • 83. 83 Process status – ps (Contd…) $ ps -u user1 $ ps -f UID PID PPID C STIME TTY TIME CMD user1 1032 1031 0 09:10:02 pts/1 00:00 bash user1 1275 1032 0 09:10:02 pts/1 00:00 ps –f
  • 84. 84 Mechanism of Process Creation • Three phases are involved in creation of process : • fork • exec • wait
  • 85. 85 Executing jobs in background In order to execute a process in background, just terminate the command line with ‘&’ $ sort –o emp.lst emp.lst & 550 # job’s PID
  • 86. 86 nohup : Log Out Safely • nohup ( no hangup) command, when prefixed to a command, permits execution of the process even after user has logged out. $ nohup sort emp.last &
  • 87. 87 Job Control Commands used for job control: bg, fg, kill, jobs $cat > test this is example of suspended process [1]+ Stopped cat >test $ jobs [1]+ Stopped cat >test $ bg %cat cat >test & $ fg %cat continued
  • 88. 88 kill command: Terminate a process $ kill 1346 $ kill 1346 121 400 $ kill -9 1346 $ kill $! # kills last background job
  • 89. 89 Scheduling jobs for later Execution at command $ at 15:15 echo “Hello” > /dev/tty <ctrl+d> Options: – l ( list ) : View list of submitted jobs -r (remove ) : Remove submitted job
  • 90. 90 Scheduling jobs using cron cron lets you schedule jobs so that they can run repeatedly. $ crontab -l 00-10 17 * * * echo “Hello” > /dev/tty day of week (0 - 6) (Sunday=0) month (1 - 12) day of month (1 - 31) hour (0 - 23) min (0 - 59)
  • 91. 91 Module 9 . Filters • Overview pr head tail cut paste sort uniq tr grep egrep fgrep
  • 92. 92 Data file $cat -n emp.lst 10 | A.K.Sharma | Director | Production | 12/Mar/1950 | 70000 11 | Sumit Singh | D.G.M | Marketing | 19/Apr/1943 | 60000 12 | Barun Sen | Director | Personnel | 11/May/1947 | 78000 23 | Bipin Das | Secretary | Personnel | 11/Jul/1947 | 40000 50 | N.k.Gupta | Chairman | Admin | 30/Aug/1956 | 64000 43 | Chanchal | Director | Sales | 03/Sep/1938 | 67000
  • 93. 93 pr : Paginating files Options to pr: -d Double spaces input. -n displays line numbers. -o n offset lines by ‘n’ spaces -h Displays header as specified instead of file name. Example: $pr emp.lst $pr -dn emp.lst $pr –h "Employee Details" emp.lst $ pr [option] [file_name]
  • 94. 94 head: Displaying the beginning of a file Options to head: -n Displays specified numbers of lines Example: $ head emp.lst $ head -n 6 emp.lst | nl $ head [option] [file_name]
  • 95. 95 tail : Displaying the end of the file Options to tail: -n Displays specified numbers of lines Example: $ tail emp.lst $ tail -6 emp.lst $tail +10 emp.lst $ tail [option] [file_name]
  • 96. 96 cut : Slitting a file vertically Options to cut: -c : cutting columns -f : cutting fields -d : specify delimeter Example: $ cut -c 1-4 emp.lst $ cut -d "|" -f1 emp.lst $ cut -d "|" -f2,4 emp.lst $ cut [option] [file_name]
  • 97. 97 paste : Pasting files Options : -d specify delimeter for pasting files Example: $ paste empno empname $ paste -d “:" empno empname $ paste [option] [file_name]
  • 98. 98 sort : Ordering a file Options: -n sorts numerically -r Reverses sort order -c Check whether file is sorted +k Starts sorting after skipping kth field -k Stops sorting after kth field -o File Write result to “File” instead of standard output -t Specify field separator $ sort [option] [file_name]
  • 99. 99 sort : Ordering a file (Contd..) Example: $ sort emp.lst $ sort -t "|" -k2 emp.lst $ sort -t "|" -k2 emp1.lst -o emp1.lst $sort -t"|" -k 3,3 -k 2,2 emp.lst
  • 100. 100 uniq : Locate repeated and no repeated lines Options: -d : selects only one copy of the repeated lines -c : displays the frequency of occurrence of all lines -u : selects only non-repeated lines Examples: $ cut -d"|" -f 4 emp1.lst > departments $ sort departments | uniq $ sort departments | uniq -d $ sort departments | uniq -c $ uniq [file_name]
  • 101. 101 tr : translating characters $tr '|/' '~~' < emp.lst Changing case for text $tr [a-z] [A-Z] < emp.lst Deleting characters $tr -d '|/' < emp.lst $ tr [options] [expression1] [expression2] [standard_input]
  • 102. 102 grep : Searching for pattern Simple search $grep “sales” emp.lst $grep d.g.m. emp.lst $grep 'jai sharma' emp.lst Ignoring case $grep -i "SALES" emp.lst $ grep [options] [file_name(s)]
  • 103. 103 grep : Searching for pattern (Contd…) Deleting specified pattern lines $grep -v "sales" emp.lst Displaying line numbers $grep -n "sales" emp.lst Counting lines containing pattern $grep -c sales emp.lst Displaying filenames $grep -l sales *
  • 104. 104 Regular Expressions Symbols Significance * Matches zero or more occurrence of previous character . Matches a single character [pqr] Matches a single character p, q or r [a-r] Matches a single character within range a – r [^pqr] Matches a single character which is not p, q or r ^pattern Matches pattern at beginning of line pattern$ Matches pattern at end of line <pattern Matches pattern at beginning of word pattern> Matches pattern at end of word
  • 105. 105 grep : Searching for pattern (Contd…) Searches for a pattern only at the beginning of a word and not anywhere on the line $grep "<man" emp.lst Searches for a pattern only at the end of a word and not anywhere on the line $grep "man>" emp.lst Using metacharacters $grep sa[kx]s*ena emp.lst $grep ag[agr][ra]r*wal emp.lst
  • 106. 106 egrep : Extended grep $grep -e sengupta -e dasgupta -e gupta emp.lst $egrep "sengupta|dasgupta|gupta" emp.lst $egrep "(sen|das|)gupta" emp.lst
  • 107. 107 fgrep : Fixed string grep Taking patterns from a File $cat -n pattern.lst 1 sales 2 gupta $fgrep -f pattern.lst emp.lst
  • 108. 108 Module 10 : Advanced Filters – sed and awk • Overview  sed- stream editor  Introduction to awk  Formatting output with printf  Logical and relational operators  Number processing  The -f option  The BEGIN and END section  Positional parameters and shell variables  Built-in variables  Making awk interactive using 'getline' statements  Arrays  Functions  The if statement  Looping constructs
  • 109. 109 sed: Stream EDitor • sed is a multi-purpose tool which combines work of several filters. • Designed by Lee McMohan. • It is used for performing non-interactive applications
  • 110. 110 sed instruction Line addressing Print 3rd line $head -n 3 emp.lst | tail -n 1 $sed '3p' emp.lst Print only 3rd line $sed -n '3p' emp.lst Print only last line $sed -n '$p' emp.lst $ sed [options] ‘address action’ [file_name]
  • 111. 111 Using multiple instructions ( -e ) Print 3rd and 6th line $sed -n -e'3p' -e'6p' emp.lst Print 3rd to 6th line $sed -n -e '3,6p' emp.lst
  • 112. 112 Context addressing $ sed -n '/gupta/p' emp.lst $ sed -n -e'/gupta/p' -e'/sharma/p' emp.lst $ sed -n -e'/gupta/,/sharma/p' emp.lst $ sed -n '/ag[agr][ar]r*wal/p' emp.lst
  • 113. 113 Writing selected lines to a file $sed -n '/director/w dlist' emp.lst $sed -n '/dirctor/w dlist > /manager/w mlist > /executive/w elist' emp.lst
  • 114. 114Text editing $sed '$i 1000|jitesh sharma' emp.lst $sed '$a 1000|jitesh sharma' emp.lst $sed '/director/d' emp.lst
  • 115. 115 Substitution $ sed 's/ | / : /' emp.lst $ sed 's/ | / : /g' emp.lst $ sed '1,5s/ | / : /g' emp.lst [address]s/string1/string2/flag
  • 116. 116 Introduction to awk • Authors : Aho, Weinberger , Kernighnan • Use : Pattern scanning and processing language • Unlike other filters, awk operates at field level
  • 117. 117 awk $ awk '/director/ { print }' emp.lst $ awk –F"|" '/sales/ {print $2,$3,$4,$6}' emp.lst $ awk –F “|” ‘NR==3, NR==6 {print NR, $2, $3, $6 }’ emp.lst $ awk <options> ‘ address {action}’ <file(s)>
  • 118. 118 Formatting output with printf $ awk -F "|" ‘/director/ { printf("%3d %-20s %-12s %dn", NR, $2, $3, $6) }' emp.lst
  • 119. 119 The logical and relational operators Logical And && Logical Or || $ awk -F "|" '$3=="director" || $3=="chairman" { print }' emp.lst $ awk -F "|" '$6 > 7500 { print }' emp.lst
  • 120. 120 Number processing $ awk -F "|" '$3=="director" { printf “%d %d n", $6, $6*0.15 }' emp.lst $ awk -F "|" '$3=="director" && $6>6700{ kount++ printf "%d %s n", kount, $2 }' emp.lst
  • 121. 121 The –f option $ cat empawk.awk $3=="director"||$6>7500 {printf"%-20s %-12s %d n", $2,$3,$6 } $ awk -F"|" -f empawk.awk emp.lst
  • 122. 122 The BEGIN and the END sections $ cat -n empawk2.awk 1 BEGIN { 2 printf "nttEmployee abstractnn" 3 } 4 $6 > 7500 { 5 kount++; tot += $6 6 printf "%3d %-20s %-12s %dn", kount, $2, $3, $6 7 } 8 END { 9 printf "nttThe average basic pay is %6dn", tot/kount 10 } $ awk –F”|” –f empawk2.awk emp.lst
  • 123. 123 Positional parameters and shell variables $ $6 > 7500 $ awk –F”|” –f empawk2.awk mpay=7800 emp.lst (change empawk2.awk line number 4 as $5>mpay )
  • 124. 124 Built-in variables $ awk 'BEGIN { FS="|" ; OFS="~"} > $5~/5[25]$/ {print $1,$2,$3,$5}' emp.lst $ awk 'BEGIN {FS="|" } > NF!=6 { > print "Record No ", NR, " has", NF, " fields"}' emp.lst $ awk '$6>6000 > { print FILENAME, $0 }' emp.lst
  • 125. 125 Making awk interactive using getline statement $ cat -n empawk3.awk 1 BEGIN { 2 printf "nEnter the cut-off basic pay : " 3 getline var < "/dev/tty" 4 printf "nttEmployee abstractnn" 5 } 6 $6 > var { 7 printf( "%3d %-20s %-12s %d n", ++kount, $2, $3, $6) 8 } $ awk –F”|” –f empawk3.awk emp.lst
  • 126. 126 Arrays $ cat -n empawk4.awk 1 BEGIN { FS = "|" 2 printf ("n%46sn", "Basic Da Hra Gross" ) 3 } 4 /sales|marketing/ { 5 da = 0.25 * $6; hra = 0.50 * $6; 6 gp = $6+hra+da; 7 tot[1] +=$6 ; tot[2] += da; 8 tot[3] +=hra; tot[4] += gp 9 kount++ 10 } 11 END { 12 printf "nt Average %5d %5d %5d %5dn", 13 tot[1]/kount, tot[2]/kount, tot[3]/kount, tot[4]/kount 14 }
  • 127. 127 Functions $ awk '{ print length()}' emp.lst $ awk 'BEGIN{ print sqrt(144)}‘ $ awk 'BEGIN{ print int(100.987)}' $ awk 'BEGIN{ print system("date")}' $ awk 'BEGIN{ print system("clear")}‘ $ awk 'BEGIN{ print index("pragati software","gati")}‘
  • 128. 128 The if statement if ($6 < 6000) { hra = 0.50 * $6 da = 0.25 * $6 } else { hra=0.40*$6 da=1000 }
  • 129. 129 Looping with for $ awk -F"|" '{ > kount[$3]++} > END{ > for(design in kount) > print(kount[design],design) > }' emp.lst
  • 130. 130 Looping with while $ cat -n newline.awk BEGIN{ FS="|" } { newline("-",50); printf("%d %s", $1, $2); } function newline(ch, num){ printf "n"; i=1 while(i<num){ printf("%c",ch); i++; } printf("n"); } $ awk -f newline.awk emp.lst
  • 131. 131 Module 11 . Introduction to shell scripting • Overview  Why shell scripting?  When not to use shell scripting?  Shell as an interpreter  Writing your first shell script (first.sh)  Different ways to execute a shell script  The sha bang statement  Some basics of scritping  The export statement  Comments in shell script
  • 132. 132 Why shell scripting? • Automating commonly used commands • Performing system administration and trouble shooting • Creating simple application
  • 133. 133 When not to use shell scripts? 1. Resource intensive task when speed is a factor 2. Heavy math operations 3. Portability 4. Structured programming 5. Subcomponents with interlocking dependencies. 6. Extensive file operations 7. Multi dimensional arrays 8. Data structures like linked lists or trees 9. Generate or manipulate graphics or GUIs. 10. Direct access to system hardware. 11. Socket programming 12. Libraries to interface with legacy code 13. Proprietary or closed source software
  • 134. 134 Shell as an interpreter Compilers i.e., C/C++ Interpreter i.e., Shell Windows Unix Prg1.c Prg1.c Prg1.obj Prg1.o Prg1.exe Prg1.out Prg1Prg1 Compilation Linking Renaming Prg1.sh Prg1 Interpretation Renaming
  • 135. 135 Writing your first shell script (first.sh) $ echo "Hello World of UNIX shell scripts….“
  • 136. 136 Different ways to execute a shell script 1. shell_name scriptName 2. scriptName 3. ./scriptName 4. /FQPN/scriptName 5. . ./FQPN/scriptName * FQPN – Full Qualified Path Name, e.g., /home/redhat/scripts/
  • 137. 137 shell_name scriptName Run this script by using any of the following commands $ bash scriptName $ ksh scriptName $ csh scriptName
  • 138. 138 scriptName To run the script like a command 1) Set the path in PATH variable 2) Set execute permission for the script Run this script by using the following command $ scriptName
  • 139. 139 ./scriptName This method can be used for that particular directory Requires execution permission Run this script by using the following command $ ./scriptName outbox inbox scripts first.sh first.sh first.sh
  • 140. 140 /FQPN/scriptName This method of running the script requires execution permission It bypasses the PATH Run this script by using the following command $ /FQPN/scriptName $ /home/scripts/first.sh homeetc / first.sh scripts
  • 141. 141 . ./FQPN/scriptName This method of running the script does not requires execution permission This method bypasses the PATH. It honors PATH user specifies. Run this script by using the following command $ . ./FQPN/scriptName
  • 142. 142 The sha bang statement • Specifies which kind of interpreter should get followed #!/bin/bash #!/bin/ksh #!/bin/csh #!/bin/more #!/bin/rm
  • 143. 143 magicScript.sh 1. #!/bin/rm 2. echo “executing this script”
  • 144. 144 The export statement 1. echo $$ 2. A=10 3. echo $A 4. ksh 5. echo $$ 6. echo $A 7. exit 8. export A 9. ksh 10. echo $A 11. A=90 12. echo $A 13. exit 14. echo $A 15. export –n A
  • 145. 145 first.sh (contd…) 1. #!/bin/bash 2. echo "Hello world of UNIX Shell Script" 3. echo "process id of your shell is: $$“ 4. echo “value of A is $A” 5. A=500 6. echo “value of A is $A”
  • 146. 146 Comments in shell scripts 1. #!/bin/bash 2. # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 3. # Pragati Software Private Limited 4. # Purpose : This is first shell script. 5. # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 6. echo "Hello world of UNIX Shell Script" 7. echo "process id of your shell is: $$“ 8. echo “value of A is $A” 9. A=500 10. echo “value of A is $A”
  • 147. 147 Module 12 . User inputs and expressions • Overview  Using read  Command line arguments  Special parameters used by the shell  Using set  Using shift  exit and exit status of the commands  Computations : expr  Various quotes on shell prompt  Arithmetic operations using 'let'
  • 148. 148 Using read $ cat -n search.sh echo -e "Enter filename : c" read filename echo -e "Enter pattern :c" read pattern grep $pattern $filename
  • 149. 149 Command line arguments $ cat -n searchPattern.sh echo "Program : $0" echo "Number of arguments specified is $#" echo "The arguments are $*" grep $1 $2
  • 150. 150 Creating USAGE messages $ cat -n usageDemo.sh if [ $# -ne 2 ] ; then echo "USAGE : addnum.sh <num1> <num2>" else echo "Addition is : `expr $1 + $2`" fi
  • 151. 151 Special parameters used by the shell Shell parameters Significance $1,$2,… Positional parameters representing command line argument $# Number of arguments specified in command line $0 Name of executed command $* Complete set of positional parameters as a single string $@ Each quoted string treated as separate argument $? Exit status of last command $$ PID of current shell $! PID of the last background job
  • 152. 152 Using set • “set” assigns its positional parameters to the positional parameters $ set 123 456 789 $ echo “$1 is $1 ,$2 is $2 ,$3 is $3”
  • 153. 153 Using shift $ cat -n shiftDemo.sh 1 #!/bin/ksh 2 NO_ARGS=$# 3 echo .Number of arguments passed $NO_ARGS. 4 echo "Argument 1 is $1" 5 echo "Argument 2 is $2" 6 echo "Argument 3 is $3" 7 echo "Argument 4 is $4" 8 echo "Argument 5 is $5" 9 echo "Argument 6 is $6" 10 echo "Argument 7 is $7" 11 echo "Argument 8 is $8" 12 echo "Argument 9 is $9" 13 shift 2 14 echo "Argument 10 is $8" 15 echo "Argument 10 is $9"
  • 154. 154 exit and exit status of command • exit • echo $?
  • 155. 155 Computations : expr $ cat -n compute.sh #!/bin/ksh A=500 B=20 echo "Two values are $A and $B" ADD=`expr $A + $B` #ADD=$((A+B)) echo "Addition is $ADD" SUB=`expr $A - $B` echo "Subtraction is $SUB" MULT=`expr $A * $B` echo "Multiplication is $MULT" DIV=`expr $A / $B` echo "Addition is $DIV"
  • 156. 156 Various quotes on shell prompt • "" (double quotes) • '' (single quotes) • `` (grave accent, back or reverse quotes)
  • 157. 157 Arithmetic operations using ‘let’ $ let sum=A+B $ echo $sum $ let mult=$A*$B $ echo $mult
  • 158. 158 Module 13 . Conditions and loops • Overview  Logical operators ( && and || )  The if condition  Using 'test' and '[ ]' to evaluate expression  String comparison operator  File comparison operator  The case statement  The while loop  The until loop  The for loop  The break statement  The continue statement
  • 159. 159 Logical operators ( && and || ) $ grep ‘director’ emp.lst && echo “Pattern found” $ grep ‘managet’ emp.lst || echo “Pattern not found”
  • 160. 160 The if condition 1. if [ condition is true ] ; then statements fi 1. if [ condition is true ] ; then statements else statements fi 1. if [ condition is true ] ; then statements elif [ condition is true ] ; then statements else statements fi
  • 161. 161 ifSearch.sh $ cat -n ifSerach.sh 1 #!/bin/ksh 2 echo -e "Enter filename : c" ; read filename 3 echo -e "Enter pattern :c" ; read pattern 4 grep $pattern $filename 5 GREP_STATUS=$? 6 if [ $GREP_STATUS -eq 1 ] ; then 7 echo "Pattern not found" 8 fi 9 if [ $GREP_STATUS -eq 2 ] ; then 10 echo "File not found" 11 fi
  • 162. 162 Using ‘test’ and ‘[ ]’ to evaluate expressions $ x=5;y=7;z=7.2 $ test $x –eq $y ; echo $? $ test $x –lt $y ; echo $? $ test $z –gt $y ; echo $? $ test $z –eq $y ; echo $? Shorthand for test $ [ $z –eq $y ] ; echo $?
  • 163. 163 String comparison operators Operators Meaning s1=s2 String s1=s2 s1!=s2 String s1 is not equal to s2 -n str String str is not a null String -z str String str is a null String str String str is a assigned and null String s1= =s2 String s1= =s2(korn and bash only)
  • 164. 164 File comparison operators Operators Meaning -f file File exist and is a regular file -r file File exist and is readable -w file File exist and is writable -e file File exist and is executable -d file File exist and is directory -e file File exist (korn and bash only) -L file File exist and is a symbolic link
  • 165. 165 fileSearch.sh $ cat -n fileSearch.sh 1 echo -e "Enter file namec" ; read filename 2 if [ -e $filename ] ; then 3 echo "Enter pattern" ; read pattern 4 grep $pattern $filename 5 GREP_STATUS=$? 6 if [ $GREP_STATUS -eq 1 ] ; then 7 echo "Pattern not found." 8 fi 9 else 10 echo "File not found." 11 fi
  • 166. 166 elifTest.sh $ cat -n elifTest.sh 1 A=500 2 B=20 3 echo "Two values are $A and $B" 4 echo -e "Enter your choice n 1)Additionn2)Subtractionn3)Multiplication n4)Divisionn" 5 read CH 6 if [ $CH -eq 1 ] ; then 7 echo "Addition is `expr $A + $B`" 8 elif [ $CH -eq 2 ] ; then 9 echo "Subtraction is `expr $A - $B`" 10 elif [ $CH -eq 3 ] ; then 11 echo "Multiplication is `expr $A * $B`" 12 elif [ $CH -eq 4 ] ; then 13 echo "Division is `expr $A / $B`" 14 fi
  • 167. 167 The case statement case condition in 1)statements ;; ---- ---- *)statements ;; esac
  • 168. 168 case test $ cat -n caseTest.sh 1 A=500 2 B=20 3 echo "Two values are $A and $B" 4 echo -e "Enter your choice n 1)Additionn2)Subtractionn3)Multiplication n4)Divisionn" 5 read CH 6 case "$CH" in 7 1) echo "Addition is `expr $A + $B`" ;; 8 2) echo "Subtraction is `expr $A - $B`" ;; 9 3) echo "Multiplication is `expr $A * $B`" ;; 10 4) echo "Division is `expr $A / $B`" ;; 11 *) echo "Invalid option" 12 esac
  • 169. 169 Matching multiple patterns $ cat -n multimatch.sh 1 echo "Do you wish to continue [y/n]" 2 read ch 3 case "$ch" in 4 y|Y) 5 echo " $ch is selected" 6 ;; 7 n|N) 8 echo " $ch is selected" 9 ;; 10 esac
  • 170. 170 The while loop Syntax :- while condition is true do commands done
  • 171. 171 whileDemo.sh 1 #!/bin/ksh 2 PATTERN_NOT_FOUND=10 3 FILE_NOT_FOUND=20 4 ch='y' 5 while [ $ch = 'y' -o $ch = 'Y' ] 6 do 7 echo -e "Enter filename : c" ; read filename 8 echo -e "Enter pattern :c" ; read pattern 9 grep $pattern $filename 2>/dev/null 10 GREP_STATUS=$? 11 if [ $GREP_STATUS -eq 1 ] ; then 12 echo "Pattern not found...." 13 fi 14 if [ $GREP_STATUS -eq 2 ]; then 15 echo "File not found..." 16 fi 17 echo "Do you want to continue [y/n]?" ; read ch 18 done
  • 172. 172 The until loop Syntax :- until condition is true do commands done
  • 173. 173 untilDemo.sh $ cat -n untilDemo.sh 1 #!/bin/bash 2 until [ $var == end ] 3 do 4 echo "Input variable #1 " 5 echo "(end to exit)" 6 read var1 7 echo "variable #1 = $var1" 8 done
  • 174. 174 The for loop Syntax : for variable in list do commands done
  • 175. 175 forDemo.sh 1. for planet in Mercury Mars Saturn do echo $planet done 1. PLANETS=“Mercury Mars Saturn “ for planet in $PLANETS do echo $planet done 1. for((i=0;i<5;i++)) do echo $i done
  • 176. 176 breakDemo.sh $ cat -n breakDemo.sh 1 LIMIT=10 2 a=0 3 while [ "$a" -le "$LIMIT" ] 4 do 5 a=$((a+1)) 6 if [ "$a" -gt 5 ];then 7 break # Skip entire rest of loop. 8 fi 9 echo -n "$a " 10 done
  • 177. 177 continueDemo.sh $ cat -n continueDemo.sh 1 LIMIT=20 # Upper limit 2 echo "Printing even numbers from 1 to 20 " 3 a=0 4 while [ $a -le "$LIMIT" ] 5 do 6 let a=a+1 7 REM=`expr $a % 2` 8 if [ $REM -ne 0 ] 9 then 10 continue # Skip rest of this particular loop iteration. 11 fi 12 echo "$a" 13 done
  • 178. 178 Module 14 . Some more scripts • Overview  Block redirection  Block commenting  Arrays  Functions
  • 179. 179 Block redirection (output to file) $ cat -n blockRedirectionDemo.sh 1 #!/bin/ksh 2 i=1 3 while [ $i -lt 10 ] 4 do 5 echo $i 6 let i=i+1 7 done>outfile.sh 8 if [ -f outfile.sh ] 9 then 10 echo "File exit" 11 else 12 echo "File does not exits" 13 fi
  • 180. 180 Block redirection (input from file) $ cat -n readFile.sh 1 while read line 2 do 3 echo $line 4 done<emp.lst
  • 181. 181 Block commenting $ cat -n blockComment.sh 1 echo "Block comment" 2 <<BLOCKCOMMENT 3 Hi Hello 4 this I can not see 5 BLOCKCOMMENT 6 echo "End of Comment"
  • 182. 182 Arrays $ cat -n arrayDemo.sh 1 #!/bin/bash 2 arr[0]=zero 3 arr[1]=one 4 arr[2]=two 5 arr[3]=three 6 arr[4]=four 7 echo ${arr[0]} 8 echo ${arr[1]} 9 echo ${arr[2]} 10 echo ${arr[3]} 11 echo ${arr[4]}
  • 183. 183 Declare variable as array $ cat -n declare_array.sh 1 #!/bin/bash 2 declare -a arr 3 for((i=0;i<10;i++)) 4 do 5 arr[$i]=$i 6 done 7 for((i=0;i<10;i++)) 8 do 9 echo ${arr[$i]} 10 done
  • 184. 184 Functions function-name ( ) { command1 command2 ..... ... commandN }
  • 185. 185 Simple function $ cat -n calc.sh 1 add(){ 2 echo "Enter num1:" 3 read num1 4 echo "Enter num2:" 5 read num2 6 echo "Addtion is `expr $num1 + $num2`" 7 } 8 add
  • 186. 186 Passing parameters to the function $ cat -n parameterPassing.sh 1 add(){ 2 num1=$1 3 num2=$2 4 5 echo "Addition is `expr $num1 + $num2`" 6 } 7 8 add 10 30
  • 187. 187 Module 15. Communication utilities • Overview  The write and wall command  Controlling messages using mesg  Sending mails
  • 188. 188 The write and wall command $ wall Hi all ctrl+d $ wall < file $ write redhat Hi redhat ctrl+d
  • 189. 189 Controlling messages using mesg $ tty /dev/tty1 $ mesg < /dev/tty2 is y $ mesg n < /dev/tty2 $ mesg < /dev/tty2 is n $ mesg is y
  • 190. 190 Sending mails $ mail [email protected] Subject: Hi This is just a short note to say hello. I don't have anything else right now. . Cc: ctrl+d $ mail
  • 191. 191 Module 16. System Administration • Overview  root : super user’s login  Administrator privileges  Starting up and shutting down the system  Disk management  find command  Backups  File compression  User administration  File system administraton
  • 192. 192 root : Super user’s login login: root password: # Prompt of root is #
  • 193. 193 su : Acquiring super user status $ su Password:*****<enter> # pwd /home/local #prompt changes, but directory doesn’t
  • 195. 195 Starting Up the System 1. Kernel is Loaded 2. Kernel then starts spawning further processes, most important is init ( PID =1). 3. init spawns further processes. init becomes parent of all shells. 4. Unix system can be set up in number of modes( Run-levels) that are controlled by init. • Single-user mode • Multi-user Mode
  • 196. 196 Shutting Down the system # shutdown -g2 # shutdown -g0 # shutdown -g0 –i6
  • 197. 197 Managing Disk Space Disk free space # df Disk Usage # du
  • 198. 198 find : Locating Files # find / -name newfile.sh –print # find . –mtime -2 -print find path_list selection_criteria action
  • 199. 199 Expressions used by find Selection Criteria Significance -name flname Selects file flname -user uname Selects file if owned by ‘uname’ -type f Selects file if it is an ordinary file -type d Selects file if it is a directory -group gname Selects file if owned by group ‘gname’ -atime +x Selects file if access time is > x days -mtime +x Selects file if modification time is > x days -newer flname Selects file if modified after ‘flname’
  • 200. 200 Expressions used by find (contd..) Action Significance -exec cmd {} ; Executes Unix command cmd -ok cmd {} ; Executes Unix command cmd, after user confirmation -print Prints selected file on standard output
  • 201. 201 Backing up files using tar Creating tar file $ tar -cvf backup.tar * Extracting tar file $ tar -xvf backup.tar
  • 202. 202 Compression and decompression of files zip and unzip zip newFile.zip filename unzip newFile.zip gzip and gunzip gzip filename gunzip filename
  • 203. 203 User Administration • For user management, Unix Provides following command:  useradd  usermod  userdel # useradd –u 210 –g dba –c “RDBMS” –d “/home/oracle” –s /bin/ksh” –m oracle # usermod –s /bin/csh oracle # userdel oracle
  • 204. 204 File System Administration fsck : File System Checking # fsck /dev/user1

Editor's Notes

  • #5: What is UNIX? The name was intended as a pun on an earlier system called ‘Multics’ (Multiplexed Information and Computing Service). This pun is the key to understand the acronym, since the word ‘Uniplexed’ does not mean anything in particular. (‘Multiplexed’ refers to a communications system able to carry many messages simultaneously.)
  • #6: Features Multi-user :- More than one user can use the machine at a time supported via terminals (serial or network connection). Multi-tasking :- More than one program can be run at a time. Hierarchical directory structure :- To support the organization and maintenance of files. Portability :- Only the kernel ( &amp;lt;10%) written in assembler tools for program development a wide range of support tools (debuggers, compilers). But only drawback of UNIX is it is lacking of GUI (Graphical User Interface) and we have to type commands for each every thing.
  • #7: Unix operating system originally developed in 1969 by a group of AT&amp;T employees at Bell Labs including Ken Thomson and Dennis Ritchie. University of California enhanced the features of UNIX. Subsequently, AT&amp;T relinquish its ownership and control over UNIX. Various companies sell their own version of UNIX.
  • #8: Unix is available in market in various flavors. Different vendors provides different operating system. Solaris is given by Sun Microsystems, AIX is given by IBM. Most popular version of Unix is Linux.
  • #14: What above command does? Displays calendar of current month. Displays calendar for specified month (i.e. month 7-July ) and year (i.e. year 2008). Displays calendar of 1752. Note: Valid year values are 1 to 9999
  • #15: %aDisplays abbreviated weekday name. %ADisplays full weekday name. %bDisplays abbreviated month name. %BDisplays full month name. %dDisplays day of month. %DDisplays date in the format of mm/dd/yy. %g Displays year in 2 digit. %GDisplays year in 4 digit.
  • #18: passwd, when invoked by ordinary user, asks for old password, after which it demands the new password twice. When u enter a password, string is encrypted by the system, and encryption is stored in file /etc/shadow.
  • #19: Unix provides two calculators – a graphical object ( xcalc command) that looks like one, and bc command. The former is available in X-window System, and is quite easy to use. The other one is less friendly, extremely powerful. In fact, there are situations when working without bc becomes quite painful. $ bc scale=2 17/7 2.42 &amp;lt;ctrl-d&amp;gt;
  • #20: Script command lets you “record” your login session in a file typescript in current directory. All the commands, their output and the error messages are stored in the file for later viewing. Hence, this can be used to maintain a log of your activities. script –a # append activities to existing file typescript script logfile#logs activities to file logfile Note: Some activities won’t be recorded properly, for example, commands used in vi.
  • #21: Command 1 :- Clears the screen. Command 2 :- Tells you filename of the terminal you are using (tty stands for teletype). Command 3 :- know your machine name uname –r: shows operating system’s version no. Command 4 :- Prints user’s login name. Command 5 :- sign off
  • #44: On Unix, the collection of data that makes up the contents of a directory or a file isn&amp;apos;t stored under a name; the data is stored as part of a data structure called an ‘inode’. In the inode, Unix stores information about which disk blocks belong to the contents of the directory or file, as well as information about who owns the directory or file and what access permissions it has. Every directory or file on Unix has its own inode. Unix doesn&amp;apos;t store the name of the directory or file in the inode. Every inode in the file system has a unique number, and the file system locates the contents of a directory or file strictly by its inode number.
  • #46: Shell acts as the mediator which interprets the command that user gives and then conveys them to the kernel which ultimately executes them. As soon as you login, sh command becomes active. Major time spent by the shell is in waiting for input from user.
  • #47: Bourne shell: Original Unix system came with Bourne shell. Created by Steve Bourne C Shell: faster than Bourne. Created by Bill Joy. Allows aliasing of commands. It also has command history feature. Korn Shell: Superset of Bourne shell. Created by David Korn of AT&amp;T’s Bell Labs.
  • #48: Two special files: /dev/null - its size always remains zero /dev/tty - refers to your own terminal
  • #49: In a pipeline, command on the left of | must use standard output, and the one on right must use standard input
  • #50: Unix provides a feature by which you can save the standard output in a file, as well as display it on the terminal (or pipe it to another process). It is made possible by tee command.
  • #51: Unix system is controlled by a number of shell variables that are separately set by the system, some during boot sequence, and some after logging in. These variables are called system variables or environment variables. You must know significance of many of them because they determine the environment in which you work. use $ set to display complete list of these variables.
  • #52: .profile is the AUTOEXEC.BAT file of Unix. .profile file must be located in your home directory, and it is executed after /etc/profile, the universal profile for all users. Universal environmental settings are kept by the administrator in /etc/profile so that they are available to all users.
  • #65: If any of the special characters mentioned above themselves occur in the pattern to be searched then they must be preceeded by a backslash(\) if they are to be treated as ordinary characters. If you want to make searching irrespective of their case, &amp;lt;Esc&amp;gt;:set ignorecaseor &amp;lt;Esc&amp;gt;: set ic
  • #66: :$s/director/member/g Replace director with member in last line :1,$s/director/member/iReplace director with member in whole file Sometimes you may like to selectively replace a string. In that case, add the ‘c’ (confirmatory) parameter as the flag at the end. Example: :1,5s/director/member/c - replace director with member in line 1 to 5(y/n/a/q/l/^E/^Y)? y (yes)make this changes n(no)skip the match a(all)make this change and all remaining ones without further confirmation q(quit)don&amp;apos;t make any more changes l(last)make this change &amp; quit ^EScoll the text one line up ^YScoll the text one line down
  • #67: Use :set all to view the complete list of options available
  • #70: Multiple file editors became available under DOS platform in early 90’s, whereas vi offered this facility from its early days. It permits you to load and edit several files simultaneously.
  • #79: The cmp command does a character-by-character comparison and indicates whether or not two files are identical. To use cmp files should be sorted. If the two files differ, cmp generates a message indicating the first point where the two files differ. E.g., file1 file2 differ: char 4, line 10 If the two files are identical, cmp simply outputs nothing (&amp;quot;silence is golden&amp;quot;), but simply returns $ prompt.
  • #80: The comm command outputs three columns: the first column identifies only those lines that are present in the first file, the second column identifies only those lines that are present in the second file, and the third column identifies those lines that are present in both files. To use comm files should be sorted. Comm can also produce selective output, using options -1, -2 or -3. $ comm -12 file1 file2 # selects only common lines
  • #81: The problem with ‘cmp’ is that it is unable to distinguish whether the difference between two files is profound or superficial. A useful alternative to the ‘cmp’ command is the UNIX ‘diff’ command. The ‘diff’ command attempts to determine the minimum set of changes needed to convert one file to another file. Maintaining several versions of a file: To use diff command files should be sorted. Take previous example for file1 and file2
  • #83: Process is an instance of a program in execution. Each process is uniquely identified by a number called PID ( Process Identifier ) that is alloted by the kernel when it is born. When you log in to a UNIX system, a process is immediately set up by the kernel: sh (for bourne shell), ksh(korn shell), bash (bourne again shell) Any command that you type in at the prompt is actually the standard input to the shell process. This process remains alive until you logout To know PID of current shell, echo $$
  • #85: Fork: A process in Unix is created with fork system call, which creates a copy of the process that invokes it. For example, when you enter a command at the prompt, the shell first creates a copy of itself. The image is practically identical to the calling process, except for few parameters like PID. When a process is forked in this way, child gets a new PID. Forking mechanism is responsible for multiplication of processes in system. Exec: Parent then overwrites the image that it has just created with the copy of the program that has to be executed. This is done by exec system call, and parent is said to exec this process. No new process is created here; existing program is simply replaced with new program. This process has same PID as the child that was just forked. Wait: Parent then executes wait system call to keep waiting for the child process to complete. When child process has completed execution, it sends a termination signal to the parent. The parent is then free to continue with other functions.
  • #86: A multitasking system lets a user do more than one job at a time. Since there can be only one job in the foreground, rest of the jobs have to run in the background.
  • #87: Background jobs cease to run, however, when a user logs out. That happens because shell dies. And, when the parent dies, its children also die. Unix system permits variation in this default behaviour, using nohup command.
  • #88: If you are using Korn or bash shell, you can use its job control facility to manipulate jobs. You can send a job to background, bring it back to foreground, suspend or even kill it. For this purpose, following commands are used: bg, fg, suspend, and kill fg and bg optionally use a job identifier prefixed by a % symbol. If you specify fg %1, the first job is brought to foreground. If you use fg %sort, sort job comes to foreground.
  • #89: Kill, by default uses signal number 15 to terminate the process. Signal 9 is also known as sure kill signal You can also kill all processes in your own system except login shell, by using special argument 0 $ kill 0# terminate all processes with signal 15 Kill $! - kills last background job
  • #91: cron lets you schedule jobs so that they can run repeatedly. It takes input from user’s crontab file. Cron process is mostly dormant, but every minute it wakes up and looks in a control file in /usr/spool/cron/crontabs) for instructions to be performed at that instant. cron is generally used by superuser to perform tasks like removing outdated files or collecting data on system performance, creating backups
  • #103: grep scans a file for occurrence of a pattern, and can display the selected pattern, line numbers in which they were found, or filenames where pattern was found. Grep can also select lines not containing the pattern
  • #105: Suppress the prefixing of filenames on output when multiple files are searched $grep -h gupta *
  • #107: Egrep command, authored by Alfred Aho, extends grep’s matching capabilities. It offers all options of grep, but its most useful feature is the facility to specify more than one pattern for search. Each pattern is separated from the other by a | (pipe) It has –f, which allows to fetch patterns from some file. egrep -f
  • #110: Designed by Lee McMohan. It is used for performing non-interactive applications
  • #111: Everything in sed is an instruction. An instruction combines an address for selectiong lines with an action to be taken on them. sed options ‘address action’ file(s) sed has two ways of addressing lines: By line number By specifying a pattern which occurs in a line Option –n is used to suppress duplicate line printing
  • #116: Sed’s strongest feature is substitution.
  • #117: This command made a late entry into the UNIX system in 1977 to augment the tool kit with suitable report formatting capabilities. Named after its authors, Aho, Weinberger and Kernighnan, awk is unquestionable the most powerful utility for text manipulation. Unlike the other filters, it can access, transform and format individual fields in a record with the greatest of ease. It also accepts regular expressions for pattern matching, has C language-type programming constructs, variables and several built-in functions, which more than suffice to meet the daily needs of report writing. By using utility programs, advanced patterns, field separators, arithmetic statements, and other selection criteria, you can produce much more complex output. The awk language is very useful for producing reports from large amounts of raw data, such as summarizing information from the output of other utility programs .
  • #118: In the line number 1 line specifier section is represented by the context address /director/. This section selects the lines that are to be processed in the action section. Moreover the print is the default action of awk there is no need to specify it if you want to print the entire line. For the purpose of the identification of fields, awk uses a contiguous string of space as the default field delimiter. This is done with –F option. Using $ prefixed variable viz. $2 $3 you can specify the field. e,g, $ awk –F “|” ‘/sales/ { print $2,$3,$5 }’ emp.lst The comma has used to delimit the field specification. These ensure that each field is separated from the other by a space. Example shown in line number2. awk also accept the line address to select lines. To select lines 3 to 6 from file filename we use following command $ awk –F”|” ‘ NR == 3, NR == 6 { print NR, $2,$3,$6}’ emp.lst
  • #119: The output in the last slide is unformatted, with the width of each field determined solely by the space it occupies in the file awk is a ‘stream formatter’, and uses the C-like printf statement to beautify the output. This statement is used with suitable format specifier to control the width and justification each field should use, irrespective of the width it has in the input. %s format will be used for string data, and %d for numeric. You can now produce a list of all the agarwals: As shown in line number 1, the name and designation have been printed in space 20 and 12 characters wide, respectively, using the ‘–’ symbol to left-justify the output. You can use following characters for formatting. CharacterDescription cASCII character dDecimal integer IDecimal integer (added in POSIX) eFloating-point format ([-]d.precisione[+-]dd) E Floating-point format ([-]d.precisione[+-]dd) fFloating-point format ([-]ddd.precision) ge or f conversion, whichever is shortest, with trailing zeroes removed GE or f conversion, whichever is shortest, with trailing zeroes removed oUnsigned octal values String xUnsigned hexadecimal number. Uses a-f for 10 to 15 XUnsigned hexadecimal number. Uses A-F for 10 to 15 %Literal %
  • #120: Line number 1 shows, how do you print the three fields for the directors or chairman? You can always write each awk program separate line and if you want to print only those lines for persons who are neither director nor chairman, you should use the != and &amp;&amp; operators instead. awk offer the ~ and !~ operators to match and negate a match, respectively. You can use this feature to print out all the chowdhury’s (spell Choudhury and chowdury) and saxena’s (spelt as saxena and saksena)as shown in line number 2. awk -F &amp;quot;|&amp;quot; &amp;apos;$2 ~ /[cC]ho[wu]dh?ury/ || $2 ~ /sa[xk]s?ena/ { print }&amp;apos; emp.lst awk can also handle numbers, both integer and floating type, all the relational tests can be handled by awk with numbers, as is done in any other language. Using operators from the set shown in the following table, as shown in line number 3. OperatorSignificance &amp;lt; Less than &amp;lt;=Less than or equal to = =Equal to !=Not equal to &amp;gt;=Greater than equal to &amp;gt;Greater than ~Match a regular expression !~Does not match a regular expression
  • #121: Like the shell, awk can perform computations on numbers. It uses the arithmetic operators +, -, *, /, and %(modulus) same as used by C or other programming languages. It also overcomes one of the major limitations of the shell; the inability to handle decimal numbers, example shown in line number 1. A user-defined variable used by awk has a special feature. No type declaration is needed, and it is initialized to zero or a null string, by default, depending on the type. awk has a mechanism of identifying the type of variable used from its context. We can now print a serial number, using the variable kount and apply it to those directors drawing a salary exceeding 6700. By default value of kount is 0.
  • #122: The programs are getting larger, you an store into file. So if the previous program was stored in the file empawk.awk, then you need to specify the program filename with the –f option : To run the empaawk.awk file type the following command at the shell prompt. $ awk –F”|” –f empawk.awk emp.lst
  • #123: awk statement are usually applied to all lines selected by the line specifier or address, and there are no addresses, then they are applied to every line of a file. If you are to print a heading, then the BEGIN section can be used quite gainfully. Similarly, if you want to print some totals after the processing is over then you should do it in the END section. The BEGIN and END sections are optional, and take the form BEGIN { action } END { action } These two sections, when present, are delimited by the body of the awk program. They also use a pair of curly braces to enclose the program. You can use these two sections to print suitable heading at the beginning, and the average salary at the end. Store the awk program in a separate file empawk2.awk, and then use the –f option. You can execute this program using command given below $ awk –F”|” –f empawk2.awk emp.lst
  • #124: The previous program can take a more generalized form if the number 7500 is replaced by a variable. To do that, the entire awk command (not just the program) should be stored in shell script, and the parameter supplied as an argument to the script. The parameter is compared with the variable. These variables are properly known positional parameters, and are identified by the shell as $1, $2, $3, etc. in the order they are presented in the line. awk also accepts these parameters without conflicting with the identifiers which also use the same notation. The only difference is that the positional parameters used by awk should be enclosed within single quotes. This will enable awk to distinguish between a positional parameter and a field identifier. So, instead of having line number 1 as the line specifier, you should generalize it as line number 2. There is another method of generalizing the previous program, without having to store the entire command sequence in a separate script file. Since both the shell and awk use variables, you can expect awk to accept values passed by the shell. If you use a variable mpay in the shell command line, then you need to make the following change in the script empawk.awk $6 &amp;gt; mpay { Run the awk program in a similar manner, but this time don’t forget to make the assignment of the shell variable mpay in the command line: shown in line 3. The assignment (mpay=7800) must be made immediately before specifying the filename. This is an unusual feature of this command, which lets you pass shell variables to an variables to an awk program.
  • #125: awk has several built-in variables. All these variables are assigned automatically by awk, though it is also possible for a user to reassign them. The major variables you can use profitably with awk are shown below. VariableFunction NRCumulative number of records read FSThe input field separator OFSThe output field separator NFNumber of fields in current record FILENAMEThe current input file FS defines the input field separator, which in this case happens to be the “|”. This is alternative to the –F option of the command, which does the same thing. When used at all it must occur in the BEGIN section so that the body of the program knows its value before it starts processing: BEGIN { FS=”|” } When neither the –F option is specified, nor is this variable defined in the BEGIN section, awk assumes the space and the tab characters as the default input field separator. Likewise, when you used the print statement with comma-separated arguments, each argument was separated from the other by a space. This is awk default output field separator, and can be reassigned using the variable OFS in the BEGIN section: BEGIN { OFS=“~” } see Line number 1. This, however, applies only to the print statement, and not printf, which formats the output strictly in accordance with the format specifier. To locate the particulars of those born in 1952 or 1955, observe that the regular expression 5[25]$ was used to anchor the pattern at the end of the fifth field.
  • #126: getline reads from the standard input, it is possible to take a line of information from the keyboard. Using the device name /dev/tty to represent the terminal, you can replace the previous sequence, by placing the getline statement in the BEGIN section. When you execute this script, it will ask you for the value which has to be used as the cut-off point : $ awk –F”|” –f empawk4.awk emp.lst
  • #127: awk handles single-dimensional arrays. The index for any array can be virtually anything; it can even be a string. No array declarations are necessary; an array is considered to be declared the moment it is used, and is automatically initialized to zero, unless initialized explicitly. You can use array to store the totals of the basic pay, da, house rent and gross pay of the sales and marketing people. Assume that the da is 25%, and the house rent 50% of the basic pay. Use the array to store the totals of each element of pay and also the gross pay. When you run the program, it outputs the average of the elements of the pay : $ awk –f empawk.awk emp.lst
  • #128: awk has several built-in functions, performing both arithmetic and string operations. A list of the major functions is presented in the table below: You may like to clear the screen before displaying an awk output on the terminal or you may want to print the system date at the beginning of the report. You can achieve all this, with the system() function. It accepts any UNIX command (or even a pipeline) as an argument, but the entire command sequence has to be enclosed within double quotes. Simply place the following statements in the BEGIN section of a awk program : BEGIN { system (“tput clear”) system(“date”) } FunctionsDescription int(x)Return the integer value of x sqrt(x)Returns the square root of x index(s1,s2)Returns the position of the string s2 in the string s1 length( )Returns the length of the argument (the complete record in case of none) substr(s1, s2, s3)Returns portion of string of length s3, starting from position s2 in string s1 split(str,arr)Splits string str into array arr Sytem(“cmd”)Executes Unix command cmd, and returns its exit status.
  • #129: awk has conditional structures with the if statement, and loops using while and for. They all execute a body of statements depending on the success or failure of the control command. The if statement can be used when the &amp;&amp; and || are found to be inadequate for certain tasks. It tests for the condition that is specified on its ‘command line’ (i.e. the line containing the if statement), and then performs the actions that follow it. Optionally, it can also perform a different set of actions if the condition is not found to be true. This statement takes the form if (condition is true) &amp;lt;statement&amp;gt; else &amp;lt;statements&amp;gt; With if you can use any relational operator, as well as the special symbols ~ and !~, to match a regular expression. They all work very well with it, and when combined with the logical operators || and &amp;&amp;, make awk programming quite easy and powerful. Note: Ther is no endif or fi terminator for the if statement used in awk.
  • #130: awk suppors two loops, for and while and they both execute the loop body as long as the control command returns a true value. for has two forms. The easier one resembles its C counterpart. A simple example illustrates the first form : for (K=1; K&amp;lt;=9;K+=2) The second form of the for loop doesn’t have a parallel in any known programming language. It has an unusual syntax : for ( k in array ) &amp;lt;commands&amp;gt; This form uses an array where k is the subscript. The unusual aspect of this form is that the subscript here is not restricted to integers alone. It can be virtually anything – even a string ! This makes it very simple to display a count of the employees, grouped according to designation. Since designation happens to be the third field, you can you $3 as the subscript of the array kount[ ].
  • #131: In the above program, user defined function newline() is defined, which takes parameters as character and number. This function can be used to print new line on the screen. The for and while loops also accept the break and continue statements, which have similar functions as their C counterparts. break causes an immediate exit from the enclosing loop, while continue starts the next iteration.
  • #135: The shell acts as an interpreter. It interprets the command to the UNIX kernel, which in turn executes on the hardware. To achieve a complex solution, often we write chaining of commands joined with various redirection operators. Sometimes we need a programming logic to be involved it our day to day activities. Hence we write series of statements in a shell scripts. Unlike compilers we neither get intermediate object or re-locatable files nor we get executables or output files. In UNIX the .out files work regardless of any extension or no extension name. Here shell script is straightway interpreted by the shell. Any failure on a particular line will terminate the interpretation.
  • #136: As in another programming languages we normally write hello world program as first program, here also we will write first “hello world program” as first.sh. In the above example, we have created a file called first.sh, it contained only 1 line which is simple Unix commands. Echo is used as print statement in Unix. The above script will just print the matter given in double quotes. To execute the script, type following line at the shell prompt and you get the similar kind of output. [redhat@unix scripts] $ bash first.sh Hello World of UNIX shell scripts…. [redhat@unix scripts] $ There are 5 different ways execute a shell script, will be discuss in next slide.
  • #137: There are 5 ways to execute a shell script. The above mentioned ways would execute a shell script. There are differences in the internal processing of the system during execution, hence one can use the concerned way depending upon the requirement of the application. Each way is explained in detailed in coming slides.
  • #138: The first way will spawn a new shell in which the entire script would be executed. Hence all the variables created through the script becomes the part of that new shell. The control is transferred back to the parent shell on the termination of script destroying all the variables which were created during execution. The script does not requires an execute permission since the invoker shell carries the execute permission. Even we don’t have to set the PATH, since we will be running the script from the source directory.
  • #139: On entering just the scriptName will give an error as command not found because the shell will assume the script as a command and will try to search it within the built in command lists, if the command is not found then it will search the command as per the directories listed in the PATH environment variable. Obviously the script is not found in the listed directories of PATH also resulting an errors as – command not found. To rectify this error, we have to add our source directory in the PATH variables by using the following command. $ export PATH=$PATH:/home/scripts $PATH is given in order to preserver the original value of PATH. Here : is a separator between the directory listing. Ensure that the directories are not ended with a /. After setting the PATH environment, definitely the command is found, but it gives a new error as – Permission denied. It causes so because yet we have not given an execute permission on the script. Use the chmod command to add the execute permission over the script. $ chmod u+x scriptName The second way will also spawn a new shell. This way is not recommended since it might not execute the script which is required by you, since it can happened that the script name given by you can be found in the other directories listed in the PATH variable prior to your source directory, E.g., consider the PATH as below. PATH=/usr/bin:/bin:/home/script Your source directory is appeared in the last and if your script name is first.sh and lets assume that already there is a script in /usr/bin which has the same as first.sh containing some other business logic, then it will execute first.sh from /usr/bin since the directory appeared prior to your directory, i.e., /home/script.
  • #140: This will not give an error related to PATH, since you have mentioned the path using the . (dot) (i.e., your current directory) and / as a separator to locate the required script. It will give an error on execute permission. Hence we have to add only the execute permission by using the following command. $ chmod u+x scriptname. This way bypasses the PATH environment variable, hence we get the accurate and desired file to be executed. This is one of the trusted way to run a script. It also spawns a new shell. In the above diagram lets assume that if we have first.sh written differently across various directories. Then we can execute the required first.sh by using the following commands. [redhat@unix scripts] $ ./first.sh (will execute first.sh from scripts directory) [redhat@unix scripts] $ ./inbox/first.sh (will execute first.sh from inbox directory) [redhat@unix scripts] $ ./outbox/first.sh (will execute first.sh from outbox directory)
  • #141: In the above diagram lets assume that if your working directory is etc, then you cant run the required script. If you just enter the script name i.e., first.sh at the shell prompt, then it will obey the PATH directory listing and the execution will take place as per the earlier mentioned 2nd way. [redhat@unix etc] $ /home/redhat/scripts/first.sh This way does not requires a dot operator in the beginning of command, since &amp;apos;home&amp;apos; is not the directory inside &amp;apos;etc&amp;apos;. It requires an execute permission. PATH environment is bypassed using this way. It also spawns a new shell.
  • #142: All the earlier mentioned ways would execute the script in a child shell. But this way will not spawn a new shell rather it will execute the script in the current shell environment. Hence all the environment variables are accessible to your script. This way does not requires execute permission. If ./ is not given then the system will search the script as per the PATH.
  • #143: The sha−bang ( #!) at the head of a script tells your system that this file is a set of commands to be fed to the command interpreter indicated. The #! is actually a two−byte ‘magic number’, a special marker that designates a file type, or in this case an executable shell script (see man magic for more details on this fascinating topic). Immediately following the sha−bang is a path name. This is the path to the program that interprets the commands in the script, whether it be a shell, a programming language, or a utility. This command interpreter then executes the commands in the script, starting at the top (line 1 of the script), ignoring comments. The sha bang statement should be the first statement.
  • #144: As discussed earlier, the #! is actually a two−byte ‘magic number’. Check whether the script is there in the directory or not. Give execute permission to the above script and run as shown below $ ./magicScript.sh Check the output. As expected line number 2 should be printed on the screen. But output is nothing. Check whether the script is there in the directory or not. When we run the script after shabang statement it follows the path which is for deleting the file. The first statement deleted the file. Hence we can not see the output of second line.
  • #145: Export statement is used to avail the value of a variable in child shells. The child shell can only refer to this exported variable in a read only fashion. Line 1 will print the current process id, i.e., the current shell&amp;apos;s process id. Then we have created and initialized variable A to 10. Line 4 will start a new shell session under the current shell. It means that it will start a child shell process. Here the value of A is unavailable unless to export it. Line number 8 will export the variable to all child shells. Doing A=90 inside the child shell will create a new variable A holding value 90. It has nothing to do with the variable A of parent shell. Use exit statement to go back to the parent shell process. Use export –n A to un-export the variable. The exported variable is available only to the child shell created onwards and not vice-versa. Use the unset command to remove current value of any variables. $ unset A #This statement will remove the current value of A
  • #146: We are continuing with script first.sh As discussed in previous slide command ‘bash’ spawns new shell and starts new process . Executing first.sh using first way also spawns new shell and starts new process. Output of line 5 will be value of A is Where value of A is set as 100. the variable values can not be used for child processes. Hence value of A is not printed on the screen. After setting value of A=500 it shows output as value of A is 500. To send value to the child processes or child shell export the values of variables using ‘export’ command $ export A After exporting value of A now output of line number 5 can be seen as expected.
  • #147: It is extremely important to put comments in shell scripts. Anything followed by # symbol is a comment and therefore ignored by the interpreter. It is good practice to make a shell script self documenting (i.e. someone with almost no scripting knowledge can read your comments in the script and reasonably understand what the script does). Maintenance of the script becomes easy.
  • #149: After executing search.sh, the script will ask user to enter file name and pattern. The variables ‘filename’ and ‘pattern’ are used to accept file name and pattern respectively. ‘read’ statement will read the data entered by the user. Input supplied through the standard input is read into the specified variables. grep then runs with variables pattern and filename as arguments. $ sign will replace the value of specified variable.
  • #150: We can give command line arguments also. $ksh serachPattern.sh sales emp.lst In above command, ‘searchPattern.sh’ id program name, ‘sales’ and ‘emp.lst’ are two parameters we are passing to the program. Parameter ‘$0’ is program name i.e. ‘searchPattern.sh’. Special variable ‘#’ gives you, number of command line arguments passed. Special variable ‘*’ gives you, all the command line arguments passed. ‘$1’ and ‘$2’ are first and second parameters passed to the command.
  • #151: (Source Code : usageTest.sh) The above program takes only 2 arguments from the command line. If more than two or less than two arguments are passed then, it shows the USAGE message guiding the user to pass only two arguments to a script. This way we can control desired number of arguments passed to a script. Here further validation on $1 and $2 can be done such as only integer values, or values in a specific range etc.
  • #153: We can set positional parameters inside the script using ‘set’ command. In above slide parameters ‘123’, ‘456’, ‘789’ are positional parameters same as that of command line arguments.
  • #154: For ksh, at a time you can pass 9 command line arguments to the script. If you want to pass more than 9 parameters, then use ‘shift’ command, as shown in slide above. In above script, we want to pass 11 arguments to the script. Shift positional parameters by 2. shift 2 So that you can read 10th and 11th parameter, as 8th and 9th parameter. But in that case, 1st and 2nd parameters gets lost. So better to save those parameters in variables for further use.
  • #155: The exit command may be used to terminate a script. Every command returns an exit status (sometimes referred to as a return status ). $? reads the exit status of the last command executed. The last command executed in the script, which is, by convention, 0 on success or an integer in the range 1 − 255 on error.
  • #156: You can do computation in scripts using ‘expr’. $ expr $A + $B As shown in above script, value of A is 500 and value of B is 20. $ sign prompts values of the variables. You want to add two values, so use addition operator and prefixed the statement with ‘expr’. You can store the value of commands using back ticks (`). ADD=`expr $A + $B` The above command, stores the value of addition in ADD variable. Another way of computation is, $((A+B)) As ‘*’ is meta character in Unix. ‘*’ to work like multiplication operator, prefix ‘*’ with ‘\’, so that it will navigate the meaning of ‘*’ and it will work as multiplication operator.
  • #157: Variable values can be extracted inside double quotes, e.g., see the following statement. $ echo &amp;quot;value of A is $A&amp;quot; $ echo value of A is $A $ echo &amp;apos;value of A is $A&amp;apos; The last command will not show the value of A because the contents between single quote is considered as hardcore string constant. The $A can only be interpreted within double quotes or no quotes. $ echo &amp;quot;Today&amp;apos;s date is date&amp;quot; The above line will be printed as it is. If we want the output of date command to be merged with echo then we should enclosed that respective command in grave accent marks, (``). Hence the modified command would be as below. $ echo &amp;quot;Today&amp;apos;s date is `date`&amp;quot;
  • #158: Computation can be done with the let statement, as shown in slide above.
  • #160: The shell provides two operators that allows conditional execution &amp;&amp; operator Syntax: cmd1 &amp;&amp; cmd2 The &amp;&amp; delimits two commands; the command cmd2 is executed only when cmd1 succeeds. In first example, if pattern ‘director’ found in file emp.lst then only the message ‘Pattern found’ is printed on the screen. || operator Syntax: cmd1 || cmd2 The || delimits two commands; the command cmd2 is executed only when cmd1 fails. It acts reverse that of &amp;&amp;. In second example, if pattern ‘manager’ does not found in file emp.lst then the message ‘Pattern not found’ is printed on the screen.
  • #161: if statement uses the above mentioned forms, same as in the other languages. Condition in of if statement is written in square brackets. The ‘if’ statement ends with ‘fi’. There is space between if , [ and ].
  • #162: As discussed earlier, $? Gives exit states of last executed command. At line number 4, ‘grep’ command is executed. At line number 4, you can check exit status of last executed command, i.e. ‘grep’ command. We can store the value of exit status in the variable. if statement is checking the value of GREP_STATUS is equal to 1 or not using ‘-eq’. You can combine more than one command using semicolon (;).
  • #163: When you use ‘if’ to evaluate expressions, you need the test statement because the true or false values returned by expressions can’t be directly handled by ‘if’. test works in three ways Compares two numbers. Compares two string’s or a single one for a null value. Checks a file’s attribute. Test doesn’t display any output but simply sets the parameter $?. Drawback:- Numeric comparison restrict to integers only. You can use various numeric comparison operators. OperatorsMeaning -eqEqual to -neNot equal to -gtGreater than -geGreater than equal to -ltLess than -leLess than equal to
  • #164: You an use various string comparison operators, shown above.
  • #165: You an use various file comparison operators, shown above.
  • #166: Above script, ‘fileSearch.sh’ is reading the file name from user. At line number 2, it is checking whether the user entered file is exist or not, using ‘-e’ option.
  • #167: Above script, is for ‘elif’ test script. If you are using ‘elif’ then there should be only one ‘fi’.
  • #168: Instead of using, nested ‘if’, as in previous script, you can use case statement.
  • #169: Above program, uses case statement for multiple cases. Line 5, reading the choice from the user. case statement, checking for the choice entered by the user. Comparing the choice with various cases. If non of the condition is matching, then ‘*’ will get called, which is used for default condition. ‘case’ statement ends with ‘esac’.
  • #170: You can give multiple choices to check one case. Line 2 is asking the user, whether user want to continue or not. read command will read the users choice. User may enter the choice as ‘y’ or ‘Y’ or ‘yes’ or ‘YES’. Taking all the options in the consideration, you can write the cases as shown in above program.
  • #171: You can loops in the script. Syntax shows, after while statement and condition there should be ‘do’ statement. ‘while’ statement should end with ‘done’.
  • #172: Above script, whileDemo.sh shows example of while loop. Line 17th, asks user whether he/she want to continue or not. Reads choice from user. if choice is either ‘y’ or ‘Y’ continue loop.
  • #173: The until construct works almost exactly the same as while. The only difference is that until executes the body of the loop so long as the conditional expression is false, whereas while executes the body of the loop so long as the conditional expression is true. Think of it as saying, &amp;quot;Execute until this condition becomes true.“.
  • #174: Above program, until loop executes the body as long as the conditional expression becomes true.
  • #175: for loop execute one for each ‘variable’ in the ‘list’ until the ‘list’ is not finished.
  • #176: Three ways you can use for loop. In way 1, there is list of all the planets as “Mercury, Mars, Saturn”. Variable ‘planet’ takes all the items one by one and prints those items on the screen. In 2nd way, instead of giving list to the for loop, the list is stored in the variable ‘PLANETS’. The variable “PLANETS” is passed to the for loop. Another variable “planet” in the for loop, taking value from the variable containing list and printing on the screen. 3rd way is C style for loop, only difference is instead of single round bracket, it uses double round brackets.
  • #177: break command causes an exit from inside a for or while loop. In above program prints value from 1,2,3… . When if condition encounters value of ‘a’ is greater than 5, it executes the break statement and exit from the while loop.
  • #178: Continue command resumes the next iteration of the enclosing for or while loop at the enclosing loop. Above script prints even numbers from 1 to 20. If condition checks whether remainder is 0, if yes then continue the loop else print the value.
  • #180: You can redirect block of data to the file using standard output, as shown above. In above script, output of while loop is stored in the file named outfile.txt.
  • #181: You can redirect block of data from the file using standard input, as shown above. In above script, input to of while loop is taken from the file named emp.lst.
  • #182: ‘#’ is used for single line commenting. If you want to give multi line comments then you do it as shown in line 2 and line 5. Whatever statements you will write in between the line 2 and line 5 those lines will be ignored by the shell.
  • #183: Bash support one-dimensional arrays. Array elements may be initialized with the variable[xx] notation. To dereference (find the contents of) an array element, use curly bracket notation, that is, ${variable[xx]}.
  • #184: Alternatively, a script may introduce the entire array by an explicit declare -a variable statement. Line 1 declares variable ‘arr’ as array using option ‘-a’. First for loop stores the value from 0 to 9 into the array ‘arr’. Second for loop displays values from the array.
  • #185: Function is series of instruction/commands. Function performs particular activity in shell i.e. it had specific work to do or simply say task. To define function use above syntax.
  • #186: In above script ‘calc.sh’, there is one function ‘add’, which is taking values from user and prints the addition value on the screen. To call the function just call it by the function name.
  • #187: You can pass parameters to the function like command line arguments. Parameters passed will be positional parameters $1, $2 and so on.
  • #189: Its name is an abbreviation of &amp;quot;write to all&amp;quot;. it displays the contents of a file or standard input to all logged-in users. Second command displays the contents of a file specified. You can write messages to specific user using command ‘write’. $ write [username] message to that user
  • #190: mesg is a Unix command that sets or reports the permission other users have to write to your terminal using the write commands. mesg is invoked as: mesg [y|n] The &amp;apos;y&amp;apos; and &amp;apos;n&amp;apos; options respectively allow and disallow write access to your terminal. When invoked with no option, the current permission is printed. I/O redirection may be used to control the permission of another tty. As shown in above slide.
  • #191: Say I want to send a short note to the person with the email address [email protected]. Here is an example of how I would do this: You can read the mail using ‘mail’ command.
  • #193: Unix system provides aspecial login name for exclusive use of system administrator; it is called root. Prompt of root is #, instead of $
  • #194: Creating user’s environment: Users often run to administrator with the complaint that a program has stopped running. It is natural for him to first try running it in a simulated environment. su command lets administrator recreate the user’s environment without taking login-password route: su –user1 This executes user1’s .profile and temporarily creates user1’s environment. This mode is terminated by hitting &amp;lt;Ctrl-d&amp;gt; or using exit command.
  • #195: passwd: change own password as well as other user’s password passwd user1 Note: when superuser uses passwd command to change a user’s password, he doesn’t have to enter old password. date : Change System date # date 10240934 Sat Oct 24 09:34:00 IST 2009 Note:argument usually an 8-character string of formatMMDDhhmm
  • #197: Ex-1 :shutdown after 2 minutes Ex-2 : shutdown immediately Ex-3: shutdown and reboot (init level 6)
  • #198: df (disk free) reports amount of free space available on the disk. Output always reports each file system separately. It has option –t (total) # df –t /dev/oracle du (disk usage) command reports usage by recursive examination of the directory tree. It has option –s (summary) # du –s /home/*# assessing space consumed by users 144208/home/user1 99999/home/user2 56432/home/user3
  • #199: This is how find operates: It recursively examines all files in the directories specified in path_list It then matches each file for one or more selection_criteria Finally, it takes some action on those selected files
  • #201: Taking action on selected files: # find /usr -mtime +30 -exec rm -f {}\; # find /home -size +2000 -atime +30 -ok rm -f {}\;
  • #204: Adding a user involves setting few parameters in /etc/passwd: 1. UID and username 2. GID and groupname 3. home directory 4. login shell 5. mailbox 6. password
  • #205: fsck command is used to check and repair a damaged filesystem.