You are on page 1of 15

SHELL SCRIPTING:

-shell is a command line interpreter


-it is interface b/w user & kernel
- it takes commands form the user and excute them
Shell are different types:
Shell developed shellprompt executetioncommand
Bourne SteveBorn $ sh
Corn devidCorn $ ksh
Cshell billjoy % csh
Bash born $ sh(or)bsh
Zsh panel $ zsh
Shell variables:
There are two types of shell variables.
Unix Defined or system defined
User Defined
Unix Defined:-these are standed variable which are always accessable.the shell
provide the values for these variables. These variables are usually used by the
system we can change the variables as per over preference an custamize the system
environment.
$ set
HOME=/user/pavan
HZ=100
IFS=space or tab or new line
LOGNAME=pavan
MAIL=usr/sped/mail/pavan
MAILCHEECK=600sec
OPTEND=1
PATH=/bin:/usr/bin:/usr/pavan:/bin:.
PS1=$primary shell prompt
Ps2= > -system prompt(default values)
SHELL=/bin/sh
TERM=vt100
TZ=ist-5:30
PATH:- Define the which shell must search in order to command .
HOME:-store default working directory of the user.
LOGNAME:-store the log name of the user.
MAIL:-Define the file where the mail of user stored.
MAILCHECK:-define the duration after which shell checks whether the user
received mail by default the values 600 sec
IFS:-define the internal felids separator which is space or tab or newline
SHELL:-define the name of you are working shell.
TERM:-define the name of the term and which you r working.
TZ:-define the name of the time zone in which you are working
User defined variable:-
These are defined by the user and used most exclusively in shell programming
Rules for creating user shell variables
The first character should be alphabet or
Eg:- -a= ,a=,b=,c=,d=
-no commas or blanks are allowed
Eg:-a,b=10 is worng
Variable names should be casesensitive
Eg:-name=,Name=,nAme=
Variable names should be a shell keywords.
SHELL keywords:
Key words are words which meaning as already been explained to the shell.
Keywords are also called as reverse words
The list of key words are in bourn shell
Echo for if untill read else case set wait fi esas uset eval
while readonly break do shift exec continue done ulimit export
exit umask return frap
Echo statements: Echo command is used to display the message on the screen and
it is used to display the values stored in a shell variable.
$echo welcome
Display output to the screen.
Double cotes are optional.
UNIX command should be in back cotes (`) in echo statement, otherwise it treats
as a text.
$echo todays date is : date
O/p - todays date is: date
$echo todays date is :`date`
o/p-todays date is : fri apr 5 9:15 Gt 2013
$echo no of files `wc l file1`
o/p no of files 10
$echo my log in name`logname`
o/p my login name is shahid
$echo my present working directory is :`pwd`
o/p my present working directory is :/home/shahid


Shell variables:
$a = 10
$b = 20
$name = shahid
$echo $a 10
$echo $b 20
$echo $name - shahid
$mypath=/home/shahid/dir1
$cd $mypath
$pwd
/home/shahid/dir1
Null variables:
A variable which has defined but has not been given any value is known as a null
variable.
$n=
$n=
Constant: It is a fixed value it doesnt change during execution of the program.
$readonly a
When the variable is made readonly the shell doesnt allow you to change their
values.
$unset a -> the variable a and its value assigned to it are erased from shell
memory.
Escape sequences:
echo shahid\n
echo pavan
\n displays in new line
\n newline $echoshahid\nshaik
\t tab $echoshahid\tshaik----shahid shaik
\b backspace $echopavan\bkumar----pavakumar
\ double quote $echo\pavankumar\
\ single quote
\\ backslash
Sample program:
Write a program to display list of files and directories and present working
directories and no of users logged into the system.
Vi sample.sh
#! /bin/bsh
ls l
pwd
who

:wq

How to execute shell script?
$sh sample.sh
$./sample.sh
We have to check the permissions and then we have to execute.
Chmod 775 sample.sh

Write a program to display the address?
#!/bin/sh
echo 100/14,20 th main\n
echo 9
th
cross maruthi nagar\n
echoBangalore\n
:wq
$./address.sh
Write a program to count no of users are currently logged into the system?
Echo The no of users :`who|wc l`
:wq users.sh
./users.sh
Read input from program?
Echo enter your name:
Read name
Echo hello $name how are you
Execution:
Enter your name: shahid
Hello shahid how are you

Read is a command to read variable value from the input user or keyboard.
Read command reads value from the keyboard up to space or enter key.
echo enter a, b, c values
read a b c
echo $a,$b,$c
enter a b c values :3 4 5
3,4,5
write a program to read two numbers and display?
Echoenter a ,b values
Read a b
Echo $a $b
Operators:
1. Arthematic operators
2. Relational operators
Numeric comparison
String comparison
3. Logical operators

1.Arthematic operators : Addition(+) ,subtraction(-)
multiplication(*),division(/),modulus division(%)
2. Relational operators: -gt (>),- lt(<) ,- ge (>=),-le (<=),-eq(=),-ne(!=)
3. Logical operators:
-And -a
-Or -o
-Nor -!
Write a program to read two numbers and display sum diff pro and div?
Echo enter 2 numbers
Read a b
C = `expr $a + $b`
Echo addition is $c
D = `expr $a - $b`
Echo subtraction is $D
E = `expr $a \ * $b`
Echo product is $E
F = `expr $a / $b `
Echo division is $F
*_ ? [] ---wild chard characters we will use \

Expr is a command to evaluating arthematic expressions.
But expr is capable of carrying out only integer arthematic.

Write a program to read 2 float numbers and display sum diff prod and divi?

Echo enter 2 numbers
Read a b
C = `echo $a + $b\bc`
Echo addition is $c
D = `echo $a - $b\bc`
Echo subtraction is $D
E = `echo $a \ * $b\bc`
Echo product is $E
F = `echo $a / $b\bc `
Echo division is $Fbc basic calculator
IF statements:
If condition
then
------------
-------------
-------------
Fi
2. if condition
Then
-------------
-----------
Else
Fi
3.ifcondition
Then
----

Elif condition
----

Elif condition
----

Fi
If 0-true
If 1-false
Cd $path
0-success
1-failure
Write a program to change directory?
Echo enter directory name
Read dir
If [cd $dir]
Then
Echo changed to $dir
Pwd
Fi
Write a program to copy a file?
Echo enter source and target file names
Read source target
If cp $source $target
Then
Echo files have been copied successfully
Else
Echo failed to copy the file
Fi

Write a program to search a string in a file?
Write a program to find greatest number of two numbers?
Echo enter two numbers
Read a b
If [$a gt $b]
Then
Echo $a is greatest number
Else
Echo $b is greatest number
fi
write a program to check given number is even or odd?
Echo enter a number
Read a
If [`expr $a%2` -eq 0]
Then
Echo even number
Else
Echo odd number
Fi
Text:-(we use conjection if)
If constantsthe are generally used in conjection text command.
Eg:-if text [condi]
If condi
If[condi]
The text command help us to find the contents of a variable the no of variables and
the type of file or kind of file permission.
The text command returns an exist status after evaluating the condition
Sy:-if text condition
Then
Commands
Else
Commands
Fi
Write a program to check how many users or working on the system
#!/usr/bin/bsh
Total= who|wc l
If text $total eq 1
Then
Echo u r only the user logged in
Else
Echo total no of users:$total
Fi
Write a program to check the given number is +ve or ve?
#!/usr/bin/bsh
Echo enter a number in
Read a
If text $a gt 0
Then
Echo the entered no is +ve
elseIf text $a eq 0
echo the entered no is 0
elseif text $a lt 0
echo the entered no is ve
fi
write a program to find out student results
#!/usr/bin/bsh
Echo enter subject marks
Read m1 m2 m3
If text $m1 ge 35
Then
If text $m2 ge 35
then
If text $m1 ge 35
Echo pass
Else
Echo fail
Elseif
Echo fail
Elseif
Echo fail
Fi
Write a program to print greatings.
Hour=date | cut c 12, 13
If[hour ge 0 a $hour lt 12]
Then
Echo Good moring
Elseif[$hour gt 12 a $hour lt 17)
Echo good afternoon
Else
Echo good evening
Fi
Fi
File text command:
-s true if the file exist and has a size>0
-f-true if the file exists and is not a directory.
-d-true if the exists is in directory
-c- true if the file exist
-r-true if the file exist it have read permission
-w-true if the file write permission
-x-true if the file execute permission
Write a program to check for ordinary file and display it contents
Echo enter a file name to be opened
Read filename
If text f $filename
Then
Cat<$fname
Else
Echo file is not present
Fi
Write a program to check given file an ordinary file or directory
Echo enter a filename
Read fname
If[-f $fname]
Then
Echoit is an ordinary file
Elseif[-d $fname]
Echo it is a directory file
Else
Echo it is not an ordinary file
Fi
Write a program to open a file if the doesnt have read permission then assign the
permission & open a file .
Echo enter a file
Read filename
If [-r $ fname]
Then
Cat <$fname
Else
Chmod u+r $fname
Cat<$fname
Fi
Write a program to append data to the file
Echo enter a file
Read fname
If[-f $fname]
Then
If[-w$fname]
Then
Echo enter the content & press ctr+d at the end
Cat>>fname
Else
Chmod u+w $fname
Cat>>fname
Fi
Else
Echo enter the data press ctr+d
Cat>fname
Fi
String text command:
Str1=str2-true if the strings are equal
Str!=str2-true if the strings not equal
-n str-true if the length of string is >0
-z str-true if the length of equal zero(=0)
Write a program to compare two strings
Echoenter str1
Read str1
Echo enter str2
Read str2
If text $str1=$str2
Then
Echo both are equal
Else
Echo both are not equal
Fi
Write a program to check given string is empty or not
Echo enter a string
Read string
If text z $string
Then
Echo string is empty
Else
Echo string is not empty
Fi
CASE CONTROL STATEMENTS
Case value in
Choice 1)
___________
___________
;;
Choice 2)
----------------
----------------
----------------
;;
Choice *
-----------------------
--------------------
;;
esac
The expression the following the case keyword is evaluate first the value that it
yields is then mathch one by one against potential choices like choice 1 choice 2
................ choice n.when match is found then shell will execute all commands in
that case upto ;; .this pair of semicolons placed at the end of each choice.
Eg:-
Echo enter a number b/w 1 to 4
Read num
Case $num in
Echo u entered one
;;
Echo u entered two
;;
Echo u entered three
;;
Echo u entered four
;;
Esac
Write a program to check given character is uppercase alphabet or lower case
alphabet or digit or special character.
Echo enter a character
Read ch
Case $ ch in
[a-z] echo u entered lowercase charecters
;;
[A-Z] echo u entere lower case charecters
;;
[0-9] echo u entered digits
;;
?) echo u entered special character
;;
Esac
Write a program to display file contents or write on to the file or execute based on
user choice
Echo enter a filename
Read fname
Echo main menu
Echo ***********
Echor-readmode
Echo w-writemode
Echo x-excute mode
Echo enter mode
Read mode
Case $ mode in
Choice r) If[-f $fname a r $fname]
Then
Cat<$fname
Fi
;;
Choice w) if[-f $fname a w$fname]
Then
Echo enter data & press ctr+d
Cat>>$fname
Fi
;;
Choice x) if[-f $fname a x $fname]
Then
$fname
Fi
;;
Choice *) echo u r execute invalid input
Esac
Exit statement:
It is used to terminate execution of shell programming
Eg:-$exit
Looping control statements:
While
Until
forloop
while:-
while condition
do
-----------
--------------
Done
Until:
Until condition
Do
------------------
-----------------
Done
Forloop:
For varable in value1,value2...................valuen
Do
-------------------
---------------------
Done
Write a program to display number from 1 to 10
Echo enter no from 1 to 10
I=1
While [$i gt 10]
Do
Echo $i
I=expr $i+1
Done
Break Or continue statements:
Break:
When the keyword break is encounted inside any loop etc automatically passes to
the first statement after the loop
While condition
Do
--------------
--------------
Break
-------------------
-------------
Done
Continue:
When the keyword continue is encounted inside loop control automatically passes
to the beginning of the loop & continue from beginning of the loop .
Write a program to display file contents of the file existing
X=0
While test $x=0
Do
Echo enter a filename
Read fname
If text ! f $name
Then
Echo $fname is not found enter current file
Continue
Else
Break
Fi
Done
Cat $ fname | more
Until: execute from false.then true it will not execute
Write a program to print no 1 to 10?
I=1
Untile [$i gt 10]
Do
Echo $i
I=expr $i+1
Done
Sleep:
Sleep commmad stop the execution of the program that specified no of seconds.
Write a program to print no from 1 to 10.
For i in 1 2 3 4 5 6 7 8 9 10
Do
Echo $i
Done
Command line arguments:
$0-first argument
$1-second argument
$./script.sh arg1 arg2.....................argn
$*-contains active string of an arguments
$#-contains no of arguments specified in the command
$?-it will store the last execution commands states.

You might also like