Sunteți pe pagina 1din 74

UNIT 2

Basics of shell programming, various types of shell available in Linux, comparisons between various shells, shell programming in bash Conditional and looping statements, Iterations, Command Substitution - expr command, arithmetic expansion, parameter passing and arguments, Shell variables, system shell variables, shell keywords, Creating Shell programs for automating system tasks.

Shell

Also called command interpreter It is the mediator, which interprets the commands that we give and then conveys them to the kernel which ultimately executes them

Different types of shells : different people implemented the interpreter function of the shell in different ways.

Bourne Shell

Creator : Steve Bourne Most popular shell...It is bundled with every unix system

This is the shell used by many Unix users Boune shell also incorporates useful features from the Korn and C shells (ksh and csh)

C Shell

Creator : Bill Joy Shell is popular with those who are seriously in Unix Programming

It has two advantages over Bourne shell Firstly it allows aliasing of commands ie, you can decide what name you want to call a command by.

Thus if the alias for ls were ls -l the command ls /usr would become ls -l /usr

It is very useful when commands which are used in time and again are renamed by you. Instead of typing the entire command you can simply use the short alias at the command line.

Second C shell has a command history feature. Previously typed commands can be recalled, since the C shell keeps track of all the commands issued at the command line...similar to the DOSKEY in MS-DOS

Korn Shell

It is very powerful It is a superset of Bourne Shell Designed by David Korn

Shell Programming

When to use Shell scripts??


Customizing your work environment Automating your daily tasks. Automating repetitive tasks Executing important system procedures Performing same operation on many files

Dont use??

When the task is too complex. Requires a high degree of efficiency. Requires a variety of software tools.

Shell Variables

Provide the ability to store and manipulate information within a shell program

The rules for building shell variables are

A variable name is any combination of alphabets, digits and an underscore('_').

No commas or blanks are allowed within a variable name

Rules (contd)

The first character of a variable name must either be an alphabet or an underscore.

Variable name should be of any reasonable length. Variable names are case sensitive

Shell Keywords

Meaning already been explained to the shell. Keywords cannot be used as variable names Also called 'Reserved words'

List of Keywords in Bourn Shell


Echo if until trap read else case wait set fi esac eval unset while break exec readonly do continue ulimit shift done exit umask

Variables in Unix

Unix-defined variables or System variables User-defined variables

System Variables
Variable PS2 PATH HOME LOGNAME MAIL Meaning System Prompt 2, default value is > Defines the path which the shell must search in order to execute any command or file Stores the default working directory of user. Stores the login name of the user. Defines the file (along with the path) where the mail of the user is stored Defines the duration after which the shell checks whether the user the user has received any mail. By default its value is 600 (seconds) Defines the Internal Field Separator. Defines the name of your default working sell Defines the name of the terminal on which you are working Defines the Time Zone

MAILCHECK IFS SHELL TERM TZ

Tips !!!!

All shell variables are string variables If a variable contain more than one word, assignment must be made using double quotes We can carryout more that one assignment in a line, like wise we can echo more that one variable's value at a time All variables defined inside a shell script die the moment the execution of script is over. A variable which has been defined but has not been given any value is known as a null variable

Tips (Contd....)

A null variable can be created in any of the following ways d=, d='', d= On echoing a null variable only a blank line will appear on the screen If a null variable is used anywhere in the command the shell manages to ignore it. Not only the system variables but also the user defined variables defined at the $ prompt or in a shell script can be displayed using the set command

1)Write following shell script, save it, execute it and note down the it's output.
# Script to print user information who currently login , current date & time # clear echo "Hello $USER" echo "Today is ";date echo "Number of user login : " ; who | wc -l echo "Calendar" cal exit 0

Read Only variables


a=10 readonly a [root@jino ~]# ./test.sh Enter Value for a: 12 echo "Enter Value for a:" read a echo $a ./test.sh: line 7: a: readonly variable 10 [root@jino ~]#

Wiping out Variable


[root@jino ~]# b=10 [root@jino ~]# unset b [root@jino ~]# echo b b [root@jino ~]# echo $b

[root@jino ~]# unset PS1 echo hi hi

Positional Parameters

Nine in number, named $1 through $9 Either we can set by the command line arguments Or use the set command

[root@jino testUSP]# set position1 position2 position3 position4 position5 [root@jino testUSP]# echo $1 position1 [root@jino testUSP]# echo $2 position2 [root@jino testUSP]# echo $3 position3 [root@jino testUSP]# echo $4 position4 [root@jino testUSP]# echo $5 position5 [root@jino testUSP]# echo $6

Write a script that reads a filename from the command line and changes the name to filename.logname of the user?

[root@jino testUSP]# touch b [root@jino testUSP]# ./chgextension b name=$1 set `who am i` mv $name $name.$1 [root@jino testUSP]# ls a.root b.root chgextension echo eco

echo $#
[root@jino testUSP]# set `date` [root@jino testUSP]# echo $1 Sat [root@jino testUSP]# echo $6 2007 [root@jino testUSP]# echo $7

[root@jino testUSP]# echo $# 6

Shift
#test2.sh echo Total number of files=$# [root@jino ~]# ./test2 * Total number of files=41

[root@jino testUSP]# set p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 p11 p12 p13 p14 p15 [root@jino testUSP]# shift 5 [root@jino testUSP]# echo $1 p6 [root@jino testUSP]# echo $9 p14

Aliases

alias l='ls -l' To determine what a command is, use the type command.

alias today='date +"%A, %B %-d, %Y"'

Shell functions
function today { echo "Today's date is:" date +"%A, %B %-d, %Y" }

Arithmetic in Shell Script


expr

a=20 b=10 c=`expr $a + $b` d=`expr $a - $b` e=`expr $a \* $b` f=`expr $a % $b` echo $c echo $d echo $e echo $f echo "*************"

expr (Contd...)

Expr is capable of carrying out only integer arithmetic. To carryout arithmetic on real numbers use bc a=100 command
b=20 c=`expr $a+$b|bc` d=`expr $a-$b|bc` e=`expr $a\*$b|bc` f=`expr $a/$b|bc` echo "Result.....\n" echo $c $d $e $f

tput

Can control the way the output is being displayed


Option Clear Cup r c Bold Blink Rev Smul Rmul Bel Lines Cols Ed Action Clear the screen Move cursor to row r and column c Bold display Blinking display Reverse video display((black on white) Start mode underline End underline mode Echo the trminals bell character Echo number of lines on the screen Echo number of columns on the screen Clear to end of the display

Exercise

Ramesh's basic salary is input through the keyboard. His dearnes allowance is 40 % of basic salary, and HRA is 20% of basic salary. Write a program to calculate his gross salary?? The distance between the two cities (in km.) is input through the key board. Write a program to convert and print this distance in meters, inches and centimeters?? The length & breadth of a rectangle and radius of a circle are input through the keyboard. Write a program to calculate area & perimeter of the rectangle, and the area &circumference of the circle

Exercise (Contd)

The file /etc/passwd contains information about all the users. Write a shell script which would receive the logname during execution, obtain information about it from /etc/passwd and display this information on the screen in easily understandable format ( Hint: cut -f 1 -d:)??? Write a shell script which will receive either the file name or the filename with its full path during execution. This script should obtain information about this file as given by ls -l and display it in proper format??

Control Instructions in Shell


Sequence control instruction Selection or decision Control Instruction Repetition or Loop Control Instruction Case Control Instruction

Decision Control

The if-then-fi statement The if-then-else-fi statement The if-then-elif-else-fi statement The case-esac statement

If-then-fi
echo Enter Source and target files \c read source echo "target filename" read target if cp $source $target then echo File Copied Successfully fi

If-then-else-fi statement
echo Enter Source and target files \c read source echo "target filename\t\t:\t\t" read target if cp $source $target then echo File Copied Successfully else echo Failed to Copy the file fi

Block diagram

Control Command

Command 1

Command 3

Command 2

Command 4

Contd...

If block : group of commands between then and else Else block : commands between else and fi Even if there is only one command to be executed in the if block the fi cannot be dropped.

Test command with if loop


echo number b/w 1 and 10 read num if test $num -lt 6 then echo i am in if loop fi

(contd...)

Test command can carry out several types of tests


Numerical tests String tests File tests

Numerical tests
Operator
-gt -lt -ge -le -ne -eq

Meaning
Greater than Less than Greater than or equal to Less than or equal to Not equal to Equal to

Other way of using test command

echo number b/w 1 and 10 read num if [ $num -lt 6 ] then echo i am in if loop fi

File tests
Option
-s file -f file -d file -c file -b file -r file -w file -x file -k file

Meaning
True if file exists and has a size greater than zero True if file exists and is not a directory True if file exists and is a directory file True if file exists and is a character special file True if file exists and is a block special file True if file exists and you have a read permission to it True if the file exists and you have a write permission to it True if file exists and you have an execute permission to it True if file exists and its sticky bit is set

echo Enter File Name read filename if [ -w $filename ] then echo Type matter to append. To stop type Ctrl D. cat >> $filename else echo No Write Permission fi

String tests
Condition
String1 = string2 String1 != string2 -n string -z string String

Meaning
True if True if True if True if True if the strings are same the striings are different the length of string is greater than zero the length of the string is zero the string is not a null string

str1="Good Morning" str2="Good Bye" [ "$str1" = "$str2" ] echo $?

Nested if-elses
If control command then do this and this fi If control command then do this and this else do this and this fi

If control command then do this else if control command then do this else do this and this fi fi

If control command then if control command then do this else do this and this fi else do this fi

Logical Operators

-a (read as AND) -o (read as OR) ! (read as NOT)

echo "Enter Marks in Five subjects" read m1 m2 m3 m4 m5 if [ $per -ge 40 -a $per -lt 50 ] then echo Third Division fi if [ $per -lt 40 ] echo $per if [ $per -gt 60 ] then echo First Division fi if [ $per -ge 50 -a $per -lt 60 ] then echo Second Division fi then echo Fail fi

per=`expr \( $m1 + $m2 + $m3 + $m4 + $m5 \) / 5`

Write a shell program to check file permissions. The program should do the following 1) It must check whether the file exists, then it must give the access rights of the file Any integer is input through the keyboard. Write a program to find out whether it is an odd or even number

echo Enter Number read number echo $number if [ `expr $number % 2` -eq 0 ] then echo Number is Even else echo Number is Odd fi

Case Control Structure


Case value in choice1) do this and this ;; choice2) do this and this ;; *) do this ;; esac

echo "Enter a number from 1 to 3" read num case $num in 1) echo You entered 1 ;; 2) echo You enterd 2 ;; 3) echo You enterd ;; *) echo I sad 1 to 3! ;;

esac
~

echo "Enter word " read word case $word in [hai]*) echo You entered 1 ;; [bye]*) echo You enterd 2 ;; c) echo You enterd ;; *) exit ;; esac

Write a menu driven program which has following options: 1) Contents of /etc/passwd 2) List of users who have currently logged in 3) Present working directory 4) Exit

Loop Control Structure


For While Until

While loop
False Control command STOP

True Command 1

Command 2

General Form
While Control command do command1 command2 done

count=1 while [ $count -le 3 ] do echo "\n Enter Values of p,n and r \c" read p n r si=`expr $p\*$n\*$r/100|bc` echo Simple Interest = Rs. $si count=`expr $count + 1` done

Until loop
Until control command do this and this and this done

i=1 until [ $i -gt 10 ] do echo $i i=`expr $i + 1` done

For loop
for control-variable in value1 value 2 value3................. do command1 command2 command3 done

For loop would execute the same sequence of commands for values mentioned in the list following the keyword in

for word in spa @ SNGIST realy Good choice 4 youngsters do echo $word done [root@jino UnixTest]# ./forTest
spa @ SNGIST realy Good choice 4 youngsters

for variable do echo $variable done

[root@jino UnixTest]# ./commandlineFor i am the way the truth and the life i am the way the truth and the life [root@jino UnixTest]#

for entry in * do if [ -d $entry ] then echo $entry fi done


[root@jino UnixTest]# ./ListDirectory 2 hai hai2

IFS (Internal Field Separator)


System Variable By Default its value is space,tab and a new line

[root@jino ~]# export IFS=/

Creating Nested Directory using for Loop


if [ $# -lt 1 ] then echo "Improper Usage: $0 path name" fi for arg in $* do if [ -d $arg ] then cd $arg else if [ -f $arg ] then echo $arg is a file exit else mkdir $arg cd $arg fi fi

oldifs="$IFS" export IFS=/

Shell Metacharacters

Special characters Also called regular expressions Used for Filename substitution, I/O redirection,Process execution, Positional parameters etc...

Filename Substitution metacharacters


Filename Substitution ? * [.....] [!.....]
A wlid card character, it can represent any combination of any number of characters eg..... ls a* --> list all files beginning with character 'a' Stands for any character eg.... ls ?? --> list all files whose names are 2 characters long Gives the shell a choice of any one character from the enclosed list eg.. ls[abcd]* --> List all the files whose first character is 'a','b','c' or 'd'

* ?

[...]

Gives the shell a choice of any one character except those enclosed in the list. eg... ls[!d-m]* ---> List all files whose first character is anything other than an alphabet in the [!...] range d to m

I/O Redirection Metacharacters


Specify from where input is to be picked up and where the output is to be sent.
I/O Redirection > < >> << m> m>&n

<< m>filename Makes filename the output of m Merges the standard output and standard error if m>&n m=1 and n=2

Select the input from the specified source eg.. cat << STOP ---> command wiil continue to read from the standard input only till the word STOP is not fed it on a fresh line

If a five digit number is input through the keyboard, write a program to calculate the sum of its digits ???
set -vx echo Enter Number read number sum=0
while [ $number -ne 0 ] do x=`expr $number%10|bc` sum=`expr $sum+$x|bc` number=`expr $number/10|bc` done echo $sum

Declaring arrays in shell

[root@jino Unix & Shell Programming]# names=( array1 array2 array3 array4 ) [root@jino Unix & Shell Programming]# echo ${names[1]} array2 [root@jino Unix & Shell Programming]#

num=4 for i in 1 2 3 4 do arr[$i]=$i i=` expr $i + 1` #echo $i done echo ${arr[4]}

S-ar putea să vă placă și