Вы находитесь на странице: 1из 148

Linux Basics and Shell

Scripting
Presentation by
V.SANTOSH

Agenda

Linux, Unix Essentials


Vi editor
Unix, Linux Architecture
File, Process
Directory Structure
Basic commands
Permissions for files, dirs
Shell Scripting
2

Linux History

1984: The GNU Project and the Free Software Foundation


Creates open source version of UNIX utilities
Covered by General Public License (GPL) ( Copy Left)
Software license enforcing open source principles
1991: Linus Trovalds
Creates open source, UNIX-like kernel, released under the
GPL
Ports some GNU utilities, solicits assistance online
Today:
Linux kernel + GNU utilities = complete, open source,
UNIX-like operating system
Packaged for targeted audiences asdistributions

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

Introduction to Linux Contd.


Linux is an Open Source OS meaning
the source code is free.
Open Source means freedom of
Speech

1)

Different Linux Distributions


( Distros)
Fedora = Test bed for new applications etc.
For testing , Free no support

2) Redhat ,SUSE = Stable used in production environment


Not free we need to subscribe, we
Get support.
3) Debian = Free, no support
Used for testing, used in production
Environment to some extent
4) Mandrinova = Free, no support
Used for testing, used in production
Environment to some extent
5) Ubuntu = Free, no support
Used for testing, used in production
Environment to some extent
Good for client machines

Features of Linux

Open Source OS
Multiuser
Multitasking
Stable and robust OS
Less prone to virus attacks

Linux principles

Everything is a file (including


hardware)
Small, single-purpose programs
Ability to chain programs together to
perform complex tasks
Avoid captive user interfaces
Configuration data stored in text

Production Environment Features

Recent Kernel Developments


Filesystems: Mundane and Advanced
Disk Striping and RAID
Parallel Processing and Clustering
Enterprise Networking Features

Unix, Linux Architecture


Typical computer system consists of:
Hardware
Operating system
Applications and utilities

Typical OS includes a user interface or


command interpreter
Unix is somewhat unique in that the
command interpreter is not integrated
with the OS but is a separate program
10

Layered Architecture of Linux and


Unix
Kernel= Performs core functions of
the OS
Interacts with Hardware
Shell= Interface between the user
and the
Kernel .
Performs the command
interpretation
Utilities, Applications
11

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

File and process


Everything in UNIX is either a file or a process.
A process is an executing program identified by a unique PID
(process identifier).
A file is a collection of data. They are created by users using text
editors, running compilers etc.
Examples of files:
a document (report, essay etc.)
the text of a program written in some high-level programming
language
instructions comprehensible directly to the machine and
incomprehensible to a casual user, for example, a collection of
binary digits (an executable or binary file);
a directory, containing information about its contents, which may
be a mixture of other directories (subdirectories) and ordinary files.

13

Linux Directory Structure


Directory

Purpose

/boot

Contains kernel, bootloader and


initrd

/bin

Essential command binaries

/dev

Device files

/etc

system configuration files.server


config files

/home

Home dir for regular users

/lib

Essential shared libraries and


kernel modules.

/proc

Pseudo filesystem used by kernel


for its
Processes

/root

Home dir for root user

/sbin

Essential command binaries


generally used by super user

14

Logging into a Linux System


Two types of login screens: virtual
consoles (text-based) and graphical
logins (called display managers)
Login using login name and password
Each user has a home directory for
personal file storage

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

Basic Command Syntax


command options arguments
Options are switches for additional info
Arguments are file or dirnames or any
Other data required by the command
Ex : ls l /root
ls = command
-l = long listing (option)
/root =Argument
18

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

File , Directory Naming


Rules
Names may be up to 255 characters
All characters are valid, except the
forward-slash
It may be unwise to use certain
special characters in file or directory
names
Some characters and space should
be protected with quotes when
referencing them
File, Dir Names are case-sensitive

21

Path = Absolute path


,relative path
Absolute pathnames
Begin with a forward slash
Complete "road map" to file location
Can be used anytime you wish to specify a file
name
Relative pathnames
Do not begin with a slash
Specify location relative to your current working
directory
Can be used as a shorter way to specify a file
name
22

Creating dir , files


Command
mkdir < dirname>

Purpose
To create a dir

touch < filename>

Creates a zero byte file or empty


file

cat > <filename>

Creates a file with content save


and exit
With ctrl +d

cat <filename>

Displays the contents of the file

tac <filename>

Displays the contents of the file in


reverse

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

How to list directory


contents ?
ls command Lists the contents of the
current directory or a specified directory
Syntax: ls [options] [files_or_dirs]

ls
ls
ls
ls

-a (include hidden files)


-l (display extra information)
-R (recurse through directories)
-ld (directory and symlink information)
25

Copy files and dirs


cp command to copy files and
directories
Syntax : cp [options] <source>
<destination>
More than one file may be copied at
a time if the destination is a
directory:
Ex : cp [options] filea fileb dest
Note : the last argument should be a
dir

26

Renaming files and dirs


mv command to move and/or rename files and
directories
Syntax : mv [options] <source>
<destination>
More than one file may be moved at a time if the
destination is a directory:
mv [options] file1 file2 destination
Note : Last argument must be a dir in case
of moving mutiple files
If the destination does not exist, the file will be
Renamed.
27

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

Check file type


Files can contain many types of data
We need to check file type with file
before opening to determine
appropriate command or application
to use
file [options] <filename>

30

Seven fundamental file


types

- 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

Important commands for system


info
Sl No

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

Lists currently running process (programs).


Show who is logged on and what they are doing.
Print your user-id and group id's
Report filesystem disk space usage (Disk Free i
how I remember it)
Disk Usage in a particular directory. provides a
summary
for the current directory.
Displays CPU processes in a full-screen GUI. A gre
way to see the
activity on your computer in real-time. Type Q to quit.
Displays amount of free and used memory in the
system.
Displays information about your CPU.

10.
11,

Display lots of information about current memory


32
usage.

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

Our Goal is to create and run a shell


scripts
34

Creating a file with vi


Type vi <filename> at the shell
prompt
After pressing enter the command
prompt disappears and you see
tilde(~) characters on all the lines
Tilde characters indicate that the line
is blank

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)

w - to move one word forward


b - to move one word backward
$ - takes you to the end of line
<enter> takes the cursor the the
beginning of next line
- (Minus) takes the cursor to the
beginning
of the current line
39

Cursor movement continued


) - moves cursor to the next
sentence
} - move the cursor to the
beginning of next paragraph
( - moves the cursor backward to
the beginning of the current
sentence
{ - moves the cursor backward to
the beginning of the current
paragraph
% - moves the cursor to the

40

Manipulating text in Command


Mode

Change (replace) Delete (cut) Yank(copy)


Letter
cl
dl
yl
Word
cw
dw
yw
Line
cc
dd
yy
Sentence c)
d)
y)
after
Sentence c(
d(
y(
before
Paragraph c{
d{
y{
above
Paragraph c}
d}
y}
below
41

Put in cursor mode


p - Paste the yanked lines from
buffer to the line below
P - Paste the yanked lines from
buffer to the line above
(the paste commands will also work
after the dd or ndd command (cut a
line and paste or
cut no. of lines and paste
respectively)
42

Navigating in the screen (Command


mode)
H - takes the cursor to the
beginning of the current screen
(Home)
L - moves to the last line of the
screen
M - moves to the middle line on the
current screen

43

File Positioning (Command


Mode)
G = takes cursor to last line of file
(Go to last line)
1G= takes cursor to first line of file
(Go first line)
XG=takes cursor to that line of the
file
(where X is the line no.)

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

Undo and redo


. u undo most recent change
U undo all changes to the current
line
Ctrl-r redo last "undone" change

46

Search in Command Mode

Search as in less or in man pages


/ <string> to search,
n next search in that order
N previous search in that order

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

System Variables continued


PATH=/usr/bin:/sbin:/bin:/usr/sbin Our
path settings
PS1=[\u@\h \W]\$ Our prompt settings
PWD=/home/student Current working
directory
SHELL=/bin/bash Our shell name
USERNAME=student User name who is
currently login to this system
54

Examples of System Defined


Variables
PS1, PS2
PS1=System Prompt 1
ex: PS1= [\u@\h \W]\$ is the default
bash prompt
PS2=System Prompt 2
Default value of PS2= >

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

Examples of System Defined


Variables
PS1, PS2
PS1=System Prompt 1
ex: PS1= [\u@\h \W]\$ is the default
bash prompt
PS2=System Prompt 2
Default value of PS2= >

57

Assigning the output of a command


to a variable
Using backquotes, we can assign the
output of a command to a variable:

filelisting=`ls -l`
echo $filelisting

58

Examples of System defined variables


(Continued)
PATH = Path variable points to the path or
directory to search for the
executables
or command ex: /bin,/sbin
LOGNAME=Login name of the user
HOME=Home Directory of the user=Default
Working directory of the user
MAIL=Path where the mail of the user is stored
Default path in RHEL for mail
/var/spool/mail/<username>
59

Examples of System defined variables


(Continued)
SHELL=Defines the default working
shell
TERM=Defines the name of the
current
working terminal

60

Rules for defining UDV and system


variable
h

UDV and System Variable)


(1) Variable name must begin with
Alphanumeric character or underscore
character (_), followed by one
or more Alphanumeric character. For e.g.
Valid shell variable are as follows
HOME
SYSTEM_VERSION

61

Rules for defining UDV and system


variable (continued)
(2) Don't put spaces on either side of
the equal sign when assigning value
to variable. For e.g. In
following variable declaration there
will be no error
# num=15

62

Rules for defining UDV and system


variable (continued)
(3) Variables are case-sensitive, just like
filename in Linux. For e.g.
#num=15
# NUM=25
# NUm=15
# nUM=21
Above all are different variable name, so
to print value 25 we have to use $ echo
$NUM
63

Rules for defining UDV and system


variable (continued)
(4) You can define NULL variable as follows (NULL
variable is variable which has no value at the time
of definition) For e.g.
# new=
# new=""
Try to print it's value by issuing following command
$ echo $new
Nothing will be shown because variable has no
value i.e. NULL variable.
(5) Do not use ?,* etc, to name your variable
names.
64

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

< used to redirect input from file


> used to redirect output to file
2> used to redirect error
& to redirect error and output
2>&1 to redirect error and
output=used
with pipes
66

Examples for redirection


tr a-z A-Z < <filename>= redirects
input
From file instead of from keyboard.
tr= translates lower case to upper case
and vice versa
find /etc name hosts > x will find all files
With the name hosts under /etcand
redirects to the file x (Syntax for find: find
<path> <criteria>)
67

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

Unix, Linux Filter commands


.cat = displays file content
.cut = used to cut a field or character from a file or output of
command
.expand = expands spaces to tab spaces in a file
. pr =format before printing

grep = searches for a string / pattern and displays the entire line

head = display first ten lines of file by default


sed = stream line editor= search and replace strings or patterns
sh

sort = sorts a file or command output in ascending or descending


order
tail =displays the last ten lines of a file

71

Linux, Unix filters continued


tac =concatenate and print files in
reverse
tee = used with mulitiple pipes
writes to file and pipes
tr = translates upper case to lower
case and vice versa
uniq =report or omit repeated lines
wc = word count, no.of lines,
no. of words, byte count from file or output
of command
72

Examples of filters in Linux,


Unix
cat hello.txt | wc | mail -s "The count"
xyz@example.com
head hello.txt
tail hello.txt
wc hello.txt
uniq hello.txt
sort hello.txt
73

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

Tail displays the last


Ten lines of a file by

default
grep Searches for a pattern and
displays

The line which contains the


pattern
sort
Sorts files
75

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

Changing permissions for file


or dir
Symbolic Method :
chmod u=rw,g=r,o=x < filename> Assign
permissions
chmod u+rw,g+w,o+x <file or dir> Append
Permissions
chmod u-w,o-r,g-r <file or dir> Delete or
remove permissions
Above permissions with chmod R <dirname>=
to
Recursively change permissions of dir
80

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

Linux Filesystem in Depth


Partitions and Filesystems
Disk drives are divided into partitions
Partitions are formatted with filesystems,
allowing users to store data
Default filesystem: ext3, the Third Extended
Linux Filesystem
Other common filesystems:
ext2 and msdos (typically used for floppies)
iso9660 (typically used for CDs)
GFS and GFS2 (typically for SANs)
83

Inodes

An inode table contains a list of all files in an ext2


or ext3 file system
An inode (index node) is an entry in the table,
containing information about a file (the
metadata), including:
file type, permissions, UID, GID
the link count (count of path names pointing to
this file)
the file's size and various time stamps
pointers to the file's data blocks on disk
other data about the file
84

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

Symbolic (or Soft) Links


A symbolic link points to another file
ls -l displays the link name and the
referenced file
lrwxrwxrwx1joejoe11Sep2518:02pf>/etc/passwd
File type: l for symbolic link
The content of a symbolic link is the name of
the file that it references
Syntax:
ln-sfilenamelinkname
90

Checking disk free space


df - Reports disk space usage
Reports total kilobytes, kilobytes used, kilobytes
free per file system
-h and -H display sizes in easier to read units
du - Reports disk space usage
Reports kilobytes used per directory
Includes subtotals for each subdirectory
-s option only reports single directory summary
Also takes -h and -H options
Applications->System Tools->Disk Usage Analyzer
or baobab - Reports disk space usage graphically
91

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

Mounting CDs and DVDs


Automatically mounted in
Gnome/KDE
Otherwise, must be manually
mounted
CD/DVD Reader
mount /media/cdrom
CD/DVD Writer
mount /media/cdrecorder
eject command unmounts and ejects

93

Mounting USB Media


Detected by the kernel as SCSI
devices
/dev/sdaX or /dev/sdbX or similar
Automatically mounted in
Gnome/KDE
Icon created in Computer window
Mounted under /media/Device ID
Device ID is built into device by
vendor
94

Archiving Files and Compressing


Archives
Archiving places many files into one
target file
Easier to back up, store, and transfer
tar - standard Linux archiving command
Archives are commonly compressed
Algorithm applied that compresses file
Uncompressing restores the original file
tar natively supports compression using
gzip and gunzip, or bzip2 and bunzip2
95

Creating, Listing, and Extracting File


Archives

Action arguments (one is required):


-c create an archive
-t list an archive
-x extract files from an archive
Typically required:
-f archivename name of file archive
Optional arguments:
-z use gzip compression
-j use bzip2 compression
-v be verbose
96

Advanced Filesystems
LVM= Logical Management for online
resizing of partitions
RAID = Redundant Array of
Inexpensive
Disks for redundancy ,
performance

97

SHELL SCRIPTING

Shell scripts are like batch files


Shell scripts are used to :
automate the tasks.
for repetitive tasks
Customising the work environment
Executing various administrative
tasks
98

Creating a shell script


# vi samplescript.sh
#!/bin/bash = Magic sh bang sequence
which indicates
interpreter
to use(not compulsory if
You are running a bash
script
in a bash shell)
echo hello world

99

Executing a shell script


sh samplescript = to execute the
script
or
chmod 700 samplescript (gives full
permissions rwx for owner of the file)
./samplescript = to execute the
script

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

Arithmetic Calculations in Shell


Script
expr = Expression=For evaluating an
arithmetic expression.
Ex: #vi calc
a=2
b=3
echo sum=`expr $a + $b`
echo sum=$sum
105

Arithmetic Operators in Shell Scripting


The following operators can be used
with
expr in Shell Scripting for calculations
1. Addition +
2. Substract
3. Multiplication \*
4. Division / (Quotient)
5. Modular Division % (Remainder)
106

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

Using Shift in Positional


Parameters
shift is a shell builtin that operates on the
positional parameters. Each time you invoke shift,
it "shifts" all the positional parameters down by
one. $2 becomes $1, $3 becomes $2, $4 becomes
$3, and so on.
By default , moves the positional parameters
to the right by one
We can shift by more than one
By giving the command shift n
Where n is the no. of times to shift
Ex: shift 3 ,shifts position by 3
111

shell script example for Shift in


positional parameters
#vi ppshift
#!/bin/bash
echo Usage: sh ppshift par1 par2 par3 par4
echo We start with $# positional parameters
echo First Parameter is $1"
echo Second Parameter is $2
echo Third Parameter is $3
# Shift parameters by one (Default is 1 you can use shift n where
#n is the no. of parameters you want to shift)
shift
echo "You now have $# positional parameters
echo First Parameter now is $1"
echo Second Parameter now is $2
echo Third Parameter now is $3
112

Important topics
Login shells and non login shells in
bash
Process Management

113

Login scripts in bash


Scripts executed when we login
/etc/profile Default profile for all users
Environmental variables
PATH
Scripts under /etc/profile.d are run in a for
loop
/etc/profile.d/* - Dir contains application
specific scripts
~/.bash_profile User specific profile
114

Non login scripts in bash


~/.bashrc = User specific Bashrc
/etc/bashrc= Default bashrc for all
users(global)
Aliases
Umasks=Provide default permission for files
and dirs
umask for root is 022
umask for regular user is 002
Functions
115

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

Structures in Shell Scripting


There are 3 types of structures in
Shell
Scripting :
1. Sequential Structure
2. Conditional Structure
3. Repetitive Structure

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

Syntax for if ..then


Syntax:
If [Condition]; then
statement
elif [Condition]; then
statement
else
statement
fi
Note:
1) If ,then is used in next statement, ;(semicolon) is not
required
2) elif is similar to else if in other programming languages
121

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

case in shell scripts


Case is generally used to select from a no.
of alternatives
We can print a menu and ask the user to
choose from a no. of alternatives.

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

Syntax of for loop


Syntax:
for variable in list of values
do
statement
done
Ex: for i in 1 2 3 4 5
do
echo $i
done
Output : 1
2
3
4
5
126

More Examples of for loop


# print nos. from 1 to 10 using for
for i in {1..10}
do
echo $i
done
Output: Prints nos. from 1 to 10 using for
Note: # is used for comment in any shell script
statements or commands in a line
beginning with # will not be executed.
127

For loop with increment other than


1
Example:
for i in $(seq 1 3 10)
do
|||
echo $i
(first no, increment, last
no.)
done
Output: 1 3 7 10 will be displayed one
below
the other.
128

For Loop with a decrement


of 1
Example:
for i in $(seq 10 -2 2)
do
|||
echo $i
(first no, increment, last
no.)
done
Output: 10 8 7 6 4 2 will be displayed
one
below the other.
129

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

Nested for loops


Nested for loops are loops within a
loop
Generally used for printing patterns
etc.
The first pass of the outer loop starts
the inner loop, which executes to
completion. Then the second pass of
the outer loop starts the inner loop
again. This repeats until the outer
loop finishes.

131

Examples of Nested for


loops
# vi nestedfor
for i in {1..5}
do
for j in (seq 1 1 $i)v
do
echo n $j
done
echo
Done
Output: prints the following pattern
1
12
123
1234
12345
132

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

While loop example


# Program to print the nos. from 1 to 10
using while
c=1
while [ $c le 10 ]
do
echo $c
c=`expr $c + 1`
done
135

Examples of Decrement in While


Loop
#Program to print the nos. from 1 to 10
In reverse order using while
c=10
while [ $c -gt 0 ]
do
echo $c
c=`expr $c - 1`
done
136

Continue, Break and Exit


While loop can be interrupted during
execution :
Continue : Reexamines the loop and
restarts
the loop
Break
: Exits the loop
Exit
: Exits the program itself

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

Until loop Example


# Program to print the nos. from 1 to 10
using until
c=1
until [ $c gt 10 ]
do
echo $c
c=`expr $c + 1`
done
139

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 in Shell Scripting


Functions are used in Shell Scripting
to:
1. Improve program readability
2. Remove repetitive code from the
scripts.
Note: Shell functions must be declared
first
142

Functions syntax
Declaring the Function :
Function Name ()
{
Command 1
Command 2
}
Calling the Function : Function Name
143

Example of Functions in Shell


Scripting
hellofn()
{
read -p Enter Your Name: name
echo $name, Welcome to the Shell
Scripting
Class
}
hellofn
144

Passing Arguments to functions


Passing argument to the functions in
shell script is easy.
Use $1, $2, .. $n variables that
represent arguments in the function
just like the positional parameters we
discussed earlier.
Note: $* indicates all arguments
together
$# indicates the total no. of arguments
145

Examples of Passing arguments to


the function
adderfn()
{
a=$1
b=$2
sum=`expr $a + $b`
echo sum=$sum
}
adderfn $1 $2
146

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

Вам также может понравиться