1.02k likes | 1.41k Views
SHELL PROGRAMMING. Objectives Introduction to Shells Introduction to shell programming Shell variables Arithmetic Operations Conditions - test Conditional and looping statements The getopts command. Shell Programming (contd.). Introduction Unix offers several command processors
E N D
SHELL PROGRAMMING • Objectives • Introduction to Shells • Introduction to shell programming • Shell variables • Arithmetic Operations • Conditions - test • Conditional and looping statements • The getopts command
Shell Programming (contd.) • Introduction • Unix offers several command processors • Called as shells • Primary interface to the user • The two basic shells are • Bourne Shell • C Shell • The shells are • Programs under execution
Shell Programming (contd.) • Introduction • The various shells Name of the Formal name Shell program sh Bourne Shell rsh Restricted Bourne Shell ksh Korn Shell rksh Restricted Korn Shell bash Bourne Again Shell csh C Shell
Shell Programming (contd.) • Introduction • The Bourne Shell • Named after the developer Stephen R. Broune • The prompt displayed by this shell is “ $ ” • Supports for processes both • Foreground and background • Pipes, filters etc. • Most unix implementations includes this shell
Shell Programming (contd.) • Introduction • C-Shell • Developed by Bill Joy • Advantages • History mechanism • Job control • Aliasing • Alternate names for commands
Shell Programming (contd.) • Introduction • Restricted Shell • Special version of Bourne Shell • Has a limited set of capabilities and privileges • Korn Shell • Named after David Korn • Up-ward Compatible extension of Bourne Shell • Has the history, job control and command aliasing
Shell Programming (contd.) • Introduction • Restricted Korn Shell • Restricted version of Korn Shell • Bourne Again Shell • Product of Free Software Foundation • Developed by Brian Fox • Extended version of Bourne Shell
Shell Programming (contd.) • Introduction • What is a shell ? • A program to interpret the commands • It reads, interprets and process the command • The shell signals it is ready by displaying a prompt • On a UNIX system there are various shells • The UNIX system starts a default shell for a user • Reading an entry from the /etc /passwd file
Shell Programming (contd.) • Introduction to shell scripts • All shells has a built in language • A user can write a script using the language and • The shell will execute that script • The script does not require compilation or linking • The shell interprets the script and • executes directly, using kernel facility • Shell programs can be used for various tasks
Shell Programming (contd.) • Introduction • Shell Script Uses • Customizing the work environment • Automating some routine tasks • Backing up all the files • Producing the sales report every month • Executing system procedures • Shutting down • formatting the disk etc…
Shell Programming (contd.) • Introduction • The # symbol marks the beginning of a comment • The execute permission for the file must be set chmod 744 program1 # program1 ls who pwd
Shell Programming (contd.) • Introduction • When a shell script is executed • The login shell creates a new shell for the script to be executed • The login-in shell waits for the new shell to terminate • Any task that can be achieved at the shell prompt • Can be achieved in the shell script
Shell Programming (contd.) • Shell variables • Provided to store and manipulate data • Any number of variables can be • Created and Destroyed • Rules for building a variable • A variable name is a combination of • Alphabets, digits and underscore (‘ _ ‘ ) • Comas and blanks are not allowed
Shell Programming (contd.) • Shell variables • Rules for building a variable ( Contd. ) • The first character must be an alphabet • They can be of any length • Variable names are case-sensitive #program2 echo What is your name\? read name echo Hello $name
Shell Programming (contd.) • Shell variables • The assignment operator • To assign values to a variable • There should be no space on either side of the assignment operator • The variable is created if it did not exist name=sam age=20 dirname=/usr/sam
Shell Programming (contd.) • Shell variables • System variables • The shell provides the values for these variables • Used by the system and govern the environment • These variables can be changed • To customize to system environment • Example • The dollar prompt can be changed $ PS1=“Next”
Shell Programming (contd.) • System variables Variable Meaning PS2 System prompt2 ( default “>” ) PATH Path which shell searches to execute HOME Default working directory LOGNAME login name IFS Internal field separator SHELL Default working shell TERM Name of the terminal TZ Time zone
Shell Programming (contd.) • System variables • The list of all system variables and values can be displayed using the set command $ set HOME=/usr/sam IFS= LOGNAME=sam MAIL=/usr/spool/mail/sam PATH=/bin:/usr/bin:/usr/sam:. ...
Shell Programming (contd.) • Shell Keywords • Borne shell has a set of predefined words • They cannot be used as variable names echo read set unset readonly shift export if else fi while do done for until case esac break continue exit return trap wait eval exec ulimit umask
Shell Programming (contd.) • Shell variables • All shell variables are string variables a=20 is stored as characters 2 and 0 • A variable can contain more than one word • The assignment must be made in double quotes $ c=“Two Words” $ echo $c
Shell Programming (contd.) • Shell variables • Assignment can be carried out in a single line • All the variables defined in a shell script • Are destroyed after the shell script execution is over • The user defined variables can be defined at the • Dollar prompt or • In a shell script $name=sam age=20 $echo Name of the boy is $name,and his age is $age Name of the boy is sam,and his age is 20
Shell Programming (contd.) • Shell variables • A null variable is a variable which is not initialized $ a=“ ” b=‘ ‘ c= • Echoing a null variable a blank line appears on the screen • The shell ignores a null variable in a command $ var1=“ ” var2=“ ” $ echo wc -l $var1 $var2 file1 178
Shell Programming (contd.) • Shell variables • Constants are variables made read-only $a=20 $readonly a • All readonly variables can be listed • By entering readonly at command prompt $ readonly
Shell Programming (contd.) • Shell variables • A variable can be removed by using the unset command $ unset b • The variable and the value are erased from the memory • Unsetting a system variable is not allowed $ unset PS1 ( error )
Shell Programming (contd.) • Command line arguments • To convey information from the user to the program • The user specifies arguments at the command line • These arguments can be accessed using • Positional parameters • The positional parameters are specified in the script as • $1 to $9 • Example- To copy a file from a srcfile to dstfile $ mycopy srcfile dstfile
Shell Programming (contd.) • Command line arguments • The statement cp $1 $2 is translated to cp srcfile dstfile • Write a shell script which accepts a filename • Changes the permissions to rwxr--r-- ( 744 ) #mycopy #usage: mycopy <source file> <destination file > cp $1 $2 echo copy completed. cat $2
Shell Programming (contd.) • Positional Parameters • The user cannot assign values to positional parameters $1=sam $2=100 (error ) • The set command can be used • to assign values to the positional parameters $ set This is my first shell script $ echo $1 $2 $3 $4 $5 $6 This is my first shell script $ set sam is good at shell programming $ echo $1 $2 $3 $4 $5 $6 sam is good at shell programming
Shell Programming (contd.) • Positional Parameters • The command in the quoting metacharacter is replaced • by the output of the command • Theses quote are called reverse quote or accent graves • Write a program to rename a filename to filename.logname • Write a program to display date in the desired format $ set ‘cat lucky‘ $ echo $1 $2 $3 $4 $5 $6
Shell Programming (contd.) • Positional Parameters • The parameter $# can be used to find out the number of • parameters from set command • parameters from the command line • The Unix metacharacter * represents all the files • when used as an argument $ prgname * # prgname #usage prgname <list of files > echo Total number of files = $#
Shell Programming (contd.) • Positional Parameters • If the number of parameters are greater than nine • The shift command can be used to shift the parameters • The $* can be used for all the positional parameters $ set a b c d e f g h i j k l m n o p $ echo $1 $2 $3 $4 $5 $6 $7 $8 $9 a b c d e f g h i $ shift 7 $ echo $1 $2 $3 $4 $5 $6 $7 $8 $9 h I j k l m n o p
Shell Programming (contd.) • Arithmetic in shell scripts • The values stored in the variables are of type character • The expr can be used to evaluate an arithmetic expression # example of arithmetic program a=20 b=10 echo ‘expr $a + $b‘ echo ‘expr $a - $b‘ echo ‘expr $a \* $b‘ echo ‘expr $a / $b‘ echo ‘expr $a % $b‘
Shell Programming (contd.) • Arithmetic in shell scripts • Terms of the expression must be separated by blanks • The priorities for arithmetic operators are /, * and % first priority + and - Second priority • If the operators of the same priority occur in an expression • Preference is give to the one occurring first $a \* $b + $c / $d $a \* $b is evaluated first • To force a particular order parenthesis must be used $a \* \( $b + $c \) / %d
Shell Programming (contd.) • Arithmetic in shell scripts • The expr can be used only for integers • For Floating point the command bc is used # example of floating point arithmetic program a=15.5 b=7.8 c=‘echo $a + $b | bc‘ d=‘echo $a - $b | bc‘ e=‘echo $a \* $b | bc‘ f=‘echo $a / $b | bc‘
Shell Programming (contd.) • Escape sequences • The echo statement can contain escape sequences Sequence Behavior \n newline character \r Carriage return \b backspace \t Tab \c cursor position
Shell Programming (contd.) • Read command • If only two values are supplied the • third one would be treated as null variable • If more than three values are supplied • The first three are supplied to a, b and c • The remaining are appended to the third #prgname echo Enter the values of a,b and c read a b c echo a b c
Shell Programming (contd.) • Exercises • A persons basic salary is entered through a keyboard • His DA is 35%of basic • HRA is 20% of his basic • Write a program to calculate his gross salary • If a five digit number is entered through a keyboard • Write a program to calculate the sum of the digits • The file /etc/passwd contains information about all users • Write a program that takes a login name as an argument,obtain information from the /etc/password • Print the information in an understandable format
Shell Programming (contd.) • Control Instructions • Specify the order of execution of the program • Sequence Control Instructions • Selection or Decision Control Instructions • Loop Control Instructions • Case Control Instructions • The Sequence Control Instructions ensures that • The instructions are executed in the same order as they appear
Shell Programming (contd.) • Decision Control • Bourne shell offers four decision making instructions • if-then-fi statement • if-then-else-fi statement • if-then-elif-else-fi statement • case-esac statement • The simplest form of if-then-fi statement is • if control command • command1 • fi
Shell Programming (contd.) • if-then-fi statement • This statement tests the exit status of the command • Weather it was executed successfully or not • The exit status is 0 on success • The exit status is 1 when not successful • Example • If cp command is successful in copying it returns 0 • If grep is successful in locating the pattern, it returns 0 • The control command can be any valid UNIX command
Shell Programming (contd.) • if-then-fi statement • If the exit status of the control command is 0 • The command1 is executed • else it is not executed • Every if statement must end with fi echo Enter source and destination files read src dst if cp $src $dst then echo file Successfully copied fi
Shell Programming (contd.) • if-then-else-fi statement echo Enter source and destination files read src dst if cp $src $dst then echo file Successfully copied # . . . . . else echo Failed to copy fi
Shell Programming (contd.) • if-then-else-fi statement • The group of commands between then and else is called • if block • The group of commands between else and fi is called • else block • Even if there is only one command to be executed • The fi cannot be dropped
Shell Programming (contd.) • Test command • Performs a test and returns the result as success or failure #Use of test command echo Enter a number from 1 to 10 read num if test $num -lt 5 then echo the number is less than five fi
Shell Programming (contd.) • Test command • The testcommand can carry out several tests • Numerical tests • Comparing numbers if they are greater, lesser or equal to • String tests • Testing if strings are same,greater than zero etc • File tests • Tests if it is a directory,character special files etc
Shell Programming (contd.) • Test command • Numerical test Operator Meaning -gt greater than -lt less than -ge greater than or equal to -le less than or equal to -ne not equal to -eq equal to
Shell Programming (contd.) • Test command # Example of numeric test echo Enter basic salary read bs if [ $bs -lt 2500 ] then hra=‘echo $bs \* 10 / 100 | bc‘ da=‘echo $bs \* 90 / 100 bc‘ else hra=500 da=‘echo $bs \* 98 / 100 | bc‘ fi gs=‘echo $bs + $hra + $da | bc‘ echo Gross salary = Rs. $gs
Shell Programming (contd.) • Test command • String test Operator Meaning string1 = string2 True if the strings are same string1 != string2 True if the strings are different -n string True if the length of the string is greater than zero -z string True if the length is zero string True if the string is not null string
Shell Programming (contd.) • Test command str1=“Good” str2=“bad” str3= [$str1 = $str2 ] echo$? [$str1 != $str2] echo$? [-n $str1 ] echo$? [-z “$str3” ] echo $? [-z $str3 ] echo$? [ “Str3” ] echo$?
Shell Programming (contd.) • Test command • If there are more than two words in a string • They have to be enclosed in double quotes for comparison str1=“Hello World” str2=“Goodbye World” [“$str1” = “$str2” ] #[$str1 = $str2 ] is an error echo$?
Shell Programming (contd.) • Test command • File test Operator Meaning -s file True if file exist & greater than zero -f file True if file exist & is not a directory -d file True if file exist & is a directory -c file True if file exist & is a character special file -b file True if file exist & block special file