Академический Документы
Профессиональный Документы
Культура Документы
Scripting
Presentation by
V.SANTOSH
Agenda
Linux History
Introduction to Linux
Unix was one of the earliest OS
It was a proprietary OS
Richard Stallman and others started the
FSF(Free Software Foundation)
GNU (GNU Not Unix) = A project of FSF
provided the shell and applications for the
new OS
Linux Trovalds in 1991 provided the kernel
And the new OS was called Linux.
4
1)
Features of Linux
Open Source OS
Multiuser
Multitasking
Stable and robust OS
Less prone to virus attacks
Linux principles
Directory Structure
All the files are grouped together in
the directory structure. The filesystem is arranged in a hierarchical
structure, like an inverted tree. The
top of the hierarchy is traditionally
called root (written as a slash / )
12
13
Purpose
/boot
/bin
/dev
Device files
/etc
/home
/lib
/proc
/root
/sbin
14
15
Virtual Consoles
By default, we have :
6 CUI virtual consoles
ctrl + alt +f1 upto f6
1 Graphical console
16
Changing Password
Passwords control access to the
system
To change your password using
GNOME, navigate to System>Preferences->About Me and then
click Password.
To change your password from a
terminal: passwd
17
Command Help
Different levels of help
whatis <command> Single line info about the
command
command help Short help with switches
man <command> complete help (manual pages)
info <command> Information regarding the
command
/usr/share/doc/<command-version> folder has files
containing documentation regarding the command
Red Hat documentation =www.redhat.com/docs
for guides,howtos etc
19
Basic commands
Command
What it does
pwd
present working directory
ls
content of pwd
ll
similar as ls, but provides additional
info on
files and
directories
ll a
includes hidden files (.name) as well
ll R
lists subdirectories recursively
ll t
lists files in chronological order
stat <file_name> provides all attributes of a file
whoami shows as who you are logged in
hostname shows on which machine you are
20
21
Purpose
To create a dir
cat <filename>
tac <filename>
23
Changing directories
Command
cd <path >
directory
cd ..
cd
cd -
Purpose
change to that
change to a directory
one level up
change to your home
directory
change to your previous
working dir
24
ls
ls
ls
ls
26
Deleting files
rm command to remove files
Syntax : rm [options] <file>...
Example:
rm -i file (interactive)= Prompts the user
before deletion
rm -r directory (recursive)
rm -f file (force)=Does not prompt the user,
deletes the file
forcefully
28
Deleting directories
rmdir <dirname> removes empty directories
rm -r <dirname> recursively removes
directory trees
Note : use rm r with caution always check
with ls R <dirname> before deletion
Or combine with i
i.e. rm ri <dirname> =Prompts before deleting
each file and the dir
29
30
- regular file
d directory
l symbolic link or soft link
b block special file Ex: hdd /dev/hda or
/dev/sda
c character special file Ex: serial port
/dev/ttyS0, parallel port /dev/lp0
p named pipe used to pass data bw
processes
s socket End point for communication
31
Command
Description
1.
2.
3.
4.
5.
6.
7.
ps
w
id
df
du
du -s
top
8.
9.
free
cat
/proc/cpuinf
o
cat
/proc/memi
nfo
uname a
10.
11,
Vi Editor
Vi is a powerful editor
Vi stands for visual editor
33
Agenda
We need to know the vi editor before
we learn shell scripting.
Use vi editor to:
create text files
edit text files
35
3 modes in vi
1. Command mode (Default mode)
2. Insert mode = to Insert Text
3. Ex mode = To save
to save and quit
quit without saving
etc.
36
Command mode in vi
Command mode is the default mode in vi
The moment you open the file with
vi <filename> , you are in command mode
In command mode is for :
i. Cursor movement
ii. Copy
iii. Paste (yank)
iv. Cut or delete
v. Go to etc.
37
Cursor movement in vi
Cursor movement is possible only in
command
mode in vi
Arrow keys may work
Standard keys for cursor movement are:
i.
h - for left
ii. l - for right
iii. j - for down
iv. k - for up
38
Cursor movement
(continued)
40
43
44
Insert Mode
Insert Mode = to insert the text
Press <insert> key to enter insert mode
after which you can type the text.
a = append after cursor
A = Append after line
i = insert before cursor
I = Insert before line
o = opens a new line
O = opens new line above
45
46
47
Search/Replace in vi editor
Search/Replace as in sed
Affects current line by default
Use m,n ranges (where m is first line and
n is the last line in the range)
or % for whole file
:1,10s/find string/replace with string/g
:%s/find string/replace with string/gi
s = search, g=more than one instance
per line , i = case insensitive
48
Ex mode
:q <enter> to exit, if no changes are
made to the file
:q! <enter> to quit forcibly
abandoning changes
:wq <enter> to save and Exit
:x <enter> same as above
ZZ to save and Exit (uppercase)
49
Configuring vi
Few configuration options :
:set number
:set autoindent
:set showmatch
:set ignorecase
50
Making configurations in vi
permanent
To make the configurations
permanent, you
have to add this in ~/.vimrc and
~/.exrc
as follows :
# vi ~/.vimrc
: se nu
51
Types of variables
Shell Variables or Local variables
Shell variables or local variables exist
only in the current shell instance.
#c=6
echo $c = Displays 6
#vi x
echo $c
sh x = Displays a blank as variable cannot be accessed within
the file since it is a local variable and not exported
Environmental variables or global variables.
These variables can be passed on to
the subshells by exporting the variables.
Add the command # export c in the command line, it becomes an
environmental variable
Then sh x will display 6
52
System Variables
System Variable
Purpose
BASH=/bin/bash
shell name
BASH_VERSION=1.14.7(1) shell version
name
COLUMNS=80 No. of columns for our screen
HOME=/home/student Our home directory
LINES=25 No. of rows for our screen
LOGNAME=student
login name
OSTYPE=Linux
Our Os type
53
55
Types of varaiables
User defined variables = variables defined
by the user. Is case sensitive, can be defined
in any case. Ex: #c=6
# echo $c
6
System defined variables =Defined by the
system used to configure the shell
environment
System defined variables are in upper case
56
57
filelisting=`ls -l`
echo $filelisting
58
60
61
62
Exit Status
used to check whether command or shell
script executed is successful or not.
(1) If return value is zero (0), command
is successful.
(2) If return value is nonzero, command
is not successful or some sort of error
executing command/shell script.
This value is know as Exit Status.
echo $? Displays the exit status.
.
65
Redirectors
Pipes
Pipes (the | character) can connect
commands:
command1|command2 Sends STDOUT of
command1 to STDIN of command2 instead
of the screen.
STDERR is not forwarded across pipes
Multiple pipes : Used to combine the
functionality of multiple tools
command1|command2|command3...etc
68
Examples of redirection
(contd).
find /etc name hosts 2> y =redirects all
errors while executing the command to the
file
Y
find /etc name &> z = will redirect both op
and error to the file z.
find /etc name 2>&1 | more=gives both
output and error from find command to the
Command more
69
Filters
In Unix and Unix-like operating systems, a
filter is a program that gets most of its data
from its standard input (the main input
stream) and writes its main results to its
standard output (the main output stream).
Unix filters are often used as elements of
pipelines. The pipe operator ("|") on a
command line signifies that the main output
of the command to the left is passed as
main input to the command on the right.
70
grep = searches for a string / pattern and displays the entire line
71
Filters
Filter
cat
pg
more
head
What it does
Concatenates and
displays files
Paginates display
For terminals
Displays a file
screenful at a time
Prints the first ten
lines of a file by
default
74
Filters (Contd.)
tail
default
grep Searches for a pattern and
displays
Advanced Linux
User administration
File System
Advanced File systems
76
User administration
useradd [ options] <username>
create user
usermod [options] <username>
modify user
userdel <username> deletes a user,
does
not delete
home dir
userdel r <username> deletes user
and his
77
Managing groups
groupadd [Options} <groupname>
creates group
Groupmod [options] <groupname>
modifies
Group
Groupdel <groupname> to delete a
group
78
Permissions
Three types of permissions on les and dirs :
Permission : what action can be performed on the le
Permissions:
1. Read (r) = to read contents of a file or list contents of
dir
2. Write (w) =to delete or modify the file, for dir to create
or del files
in the dir
3. Execute (x ) = to execute the le as a program, for dir
to cd to that dir
Permissions are given for User<owner>, group that owns
The file or dir and others (everyone else)
79
Numeric Permissions
r-4, w-2, x-1
Ex: chmod 755 <dir or file>
Gives rwx for user(owner),rw for group and
others
Viewing permissions:
ls l <file or dirname> see the first column
-rwxrw-rw- = 1 bit type of file, 2,3,4
user(owner),
5,6,7 for group,8,9,10 for others
81
Filesystems
1. File System is a method for storing and organizing computer files and
the data they contain, to make it easy to find and access the files.
2. It may use a data storage device such as hard disk or CD-ROM and
involve maintaining the physical location of the files.
3. Mostly File System make use of an underlying data storage device
that offers access to an
array of fixed-size blocks called Sectors, generally of 512 bytes each.
4. They typically have directories which associates filename with files.
5. Examples are FAT (File Allocation Table), NTFS, ext2,ext3, ext4 etc.
82
Inodes
Directories
The computer's reference for a file is
the inode number
The human way to reference a file is
by file name
A directory is a mapping between the
human name for the file and the
computer's inode number
85
cp and inodes
The cp command:
Allocates a free inode number,
placing a new entry in the inode
table
Creates a dentry in the directory,
associating a name with the inode
number
Copies data into the new file
86
mv and inodes
If the destination of the mv command is on the
same file system as the source, the mv command:
Creates a new directory entry with the new file
name
Deletes the old directory entry with the old file
name
Has no impact on the inode table (except for a
time stamp) or the location of data on the disk: no
data is moved!
If the destination is a different filesystem, mv acts
as a copy and remove
87
rm and inodes
The rm command:
Decrements the link count, thus
freeing the inode number to be
reused
Places data blocks on the free list
Removes the directory entry
Data is not actually removed, but will
be overwritten when the data blocks
are used by another file
88
Hard Links
A hard link adds an additional pathname to
reference a single file
One physical file on the filesystem
Each directory references the same inode number
Increments the link count
The rm command decrements the link count
File exists as long as at least one link remains
When the link count is zero, the file is removed
Cannot span drives or partitions
Syntax:
ln filename [linkname]
89
Removable Media
Mounting means making a foreign filesystem
look like part of the main tree.
Before accessing, media must be mounted
Before removing, media must be unmounted
By default, non-root users may only mount
certain devices (cd, dvd, floppy, usb, etc)
Mountpoints are usually under /media
RH033-RH033-RHEL5-en-2-20070306
Copyright 2007 Red Hat, Inc.
All rights reserved
92
93
Advanced Filesystems
LVM= Logical Management for online
resizing of partitions
RAID = Redundant Array of
Inexpensive
Disks for redundancy ,
performance
97
SHELL SCRIPTING
99
100
Shell keywords
echo = for output prints whatever is
mentioned after that word on the screen
( can be redirected)
Ex: echo hello = displays hello
read = for input
Ex: read name takes input from keyboard and
stores the value in the variable name.
(other keywords will be discussed throughout
This presentation)
101
Shell Keywords
echo
read
if
fi
else
set
do
case
shift
export
then
for
while
until
readonly
eval
esac
break
continue
exit
return
unset
umask
102
Handling Output
echo = Used to display on the screen
Ex: echo hello world
103
Handling Input
read <Variable> = to take input from keyboard
and store the value in the
variable
Ex: The following script takes the name as input
from keyboard and displays the name and
welcome statement
# vi inout.sh
echo n enter your name:
read name
echo $name,welcome to the Shell Scripting class
104
Assignment 2
Write a program to input 2 nos.,
Calculate and print the following :
1. Sum
2. Difference
3. Product
4. Quotient
5. Remainder
107
Positional Parameters
Positional parameters is a convenient
way
to pass data to a program.
can be considered as variables
defined by the shell.
These are named $1 to $9
While $0 indicates the program
name.
108
Example of Positional
Parameters
You can write a program to add 2
nos. and pass values to the program.
#vi adder
echo usage: sh adder $1 $2 ex: sh
adder 2 3
sum=`expr $1 + $2`
echo $sum
109
Assignment 3
Write a program to pass values to a
program
from command line and perform the
following:
Input studentname marks in 5 subjects
,
Calculate and print the following:
Studentname Phy Chem Maths Eng Hin
(Marks)
Total marks and average marks
110
Important topics
Login shells and non login shells in
bash
Process Management
113
Test command
Evaluates boolean statements for use in conditional
execution
Returns 0 for true
Returns 1 for false
Examples in long form:
$test"$A"="$B"&&echo"Stringsareequal"
$test"$A"eq"$B"&&echo"Integersareequal"
Examples in shorthand notation:
$["$A"="$B"]&&echo"Stringsareequal"
$["$A"-eq"$B"]&&echo"Integersareequal"
116
Assignment
Write a shell script to compare 3 nos.
using test
Write a shell script to compare 2
strings
using test
117
118
Sequential Structure
In Sequential structure, commands
are
executed in sequence one after the
other.
Ex: All the shell scripts we discussed so
far are sequential structures.
119
Conditional Structures
In conditional structures,
Commands are executed based on a condition.
Similar to conditional control structures in
programming languages, there are some
differences.
1. The if condition tests the success of a Linux
command, not an expression.
2. The end of an if-then command must be
indicated with the keyword fi, and
3. the end of a case command is indicated with
the keyword esac.
120
Assignment 4
1) Write a shell script to input 2 nos.
and
print whether they are equal or not. If
not
Equal, print the greatest of the 2 nos.
Using if..then
2) Write a shell script to input 2
strings
and display whether they are equal or
not
122
123
Syntax of case
Syntax :
Case choice in 1) command ;;
2) command;;
3) Command;;
*) echo invalid entry;;
Esac
Note: 1) * indicates a value other those
mentioned in the menu.
2) every option is terminated with ;;
124
Repetitive Structures
In repetitive structures, commands
are
executed repetitively in a loop
Ex:
1) for Loop
2) while Loop
3) until Loop
125
Assignment 5
1) Write a shell script to print the nos.
from
1 to 10 and their squares using for.
2) Write a shell script to print the even
and
odd nos. from 1 to 10 using for
130
131
Assignment 6
1. Write a program to print the
following
Patterns :
i) 12345 ii) *
1234
**
123
***
12
****
1
*****
133
While Loop
The commands within a while loop are
executed repetitively as long as
the condition is true.
Syntax :
while [ condition]
do
Command 1
Command 2
done
134
137
Until Loop
The commands within an until loop are
executed repetitively as long as
the condition is false.
Syntax :
until [ condition]
do
Command 1
Command 2
done
138
Assignment 7
Write a program to print the even
and odd nos. between 1 and 10
using while and until
140
Assignment 8
Write a shell script to print the nos.
from 1 to 10 in reverse order using
until.
Write a shell script to input a no.
and check whether it is prime or not.
141
Functions syntax
Declaring the Function :
Function Name ()
{
Command 1
Command 2
}
Calling the Function : Function Name
143
Assignment 9
Write a shell script using functions
and passing arguments to functions
to :
1. Copy
a file
2. Move a file or rename filea to fileb
Note :first create a small textfile and
create the
above functions.
147
References
http://www.versageek.com/ksh_muni
x.html
http://www.computerrealm.net/types-of-operatingsystems/
http://techforum4u.com/content.php/
339-File-System-In-Operating-System
148