Anda di halaman 1dari 15

COMP307 Lab Work 5 Shell A shell is a command line interpreter. It takes commands and executes them.

As such, it implements a programming language. Three most widely used shells in UNIX are Bourne shell( !in sh", # shell, and $orn shell. Shell scripts A shell script or a shell program is a series o% commands put in a %ile and executed !y the &hell. 'e will use Bourne shell to create shell scripts Why and where it is used Why Shell scripts? &ince the user cannot interact with the kernel directly, &hell programming skills are a must to !e a!le to exploit the power o% UNIX to the %ullest extent. A shell script can !e used %or (ariety o% tasks and some o% them are listed !elow. ses o! Shell scripts ). #ustomi*ing your work en(ironment +or ,xample ,(ery time you login, i% you want to see the current date, a welcome message, and the list o% users who ha(e logged in you can write a shell script %or the same. -. Automating your daily tasks. +or example, to !ack up all the programs at the end o% the day. .. Automating repetiti(e tasks. /. ,xecuting important system procedures, like shutting down the system, %ormatting a disk, creating a %ile system etc. 0. 1er%orming some operations on many %iles. "irst si#ple S$%LL script #reate a %ile named &&) (shell script )" and type the %ollowing as content. %&a#ple' runnin( #ultiple linu& co##ands in one (o ) * SS' ls who pwd &a(e the %ile and type the %ile name in command line and the %ile is executed as %ollows. )+, SS' SS') Co##and not "oundThe reason %or this message is , the path o% this command should !e speci%ied. )+, -.SS' SS') Per#ission /eniedNow you do not ha(e the permission to execute the %ile. That is the de%ault permission gi(en %or any %ile is with out execute permission. 2ow to know the de%ault permission3 Type the command ls 0l This command will list the permission and other details o% the %ile in current directory.

change the permission and execute the %ile again. S$%LL 1ariables The (aria!les in the Bourne &hell are classi%ied as 4 ser de!ined 1ariables ) de%ined !y the user %or his use (e.g age5.-". 4 %n1iron#ental 1ariables ) de%ined !y shell %or its own operations (1AT2,267,,T,87,96:NA7,, 1&),&2,99 e.t.c". 4 Prede!ined 1ariables ) reser(ed (aria!les used !y the shell and unix commands %or speci%ying the exit status o% command, arguments to the shell scripts, the %ormal parameters e.t.c. %&a#ples ) ;name5Ali <(aria!le name is assigned a (alue Ali ;echo =name <Ali will !e displayed ;echo 2ello =name > , 'elcome to =267, <see output o% this in your computer *SS echo %nter your na#e read na#e title2Mrecho hello ,title ,na#e 34 Welco#e to ,$OM% %scape Se5uences used with echo co##and to control the output are) ??! (Back &pace" ??% (+orm %eed" ??n (New 9ine " ??r (#arriage 8eturn" ?c (1laces the cursor at the end o% the output o% echo , so that the read command will wait %or its input at the same line. To read standard input into a shell script use the read command. +or example@ %&a#ple6 interacti1e shell ) * SS6 * sa(e) SS6 * 7n interacti1e shell script echo What is your na#e8? read na#e echo $ello ,na#e- 97M7S:% This prompts the user %or input, assigns this to the (aria!le name and then displays the (alue o% this (aria!le to standard output. I% there is more than one word in the input, each word can !e assigned to a di%%erent (aria!le. Any words le%t o(er are assigned to the last named (aria!le. +or example@ %&a#ple3 with #ore than one word input ) * SS3 * sa(e) SS3

echo ;Please enter your surna#e8n; echo ;!ollowed by your !irst na#e) 8c; read na#e' na#e6 echo ;Welco#e to /oCS%4 < 4 ,na#e6 ,na#e'; %&a#ple= copies !ile !ro# !irst to second) * SS= * sa(e) SS= * :his script takes two !ile na#es and copies the !irst !ile into the second one echo >Please %nter source !ile na#e )8c? read source echo >%nter the tar(et !ile na#e )8c? read tar(et cp ,source ,tar(et echo !ile ,source is copied into the ,tar(et Co##and Substitution ) +ormat %or command su!stitution is @ 1ar2@co##and@ (where A A is !ack Buote" %&a#ples) echo @date@ < It will display the output o% date command echo there are @who A wc Bl@ users workin( on the syste# o% this 7rith#etic in S$%LL script Carious %orms %or per%orming computations on shell (aria!les using e&pr command are @ e&pr 1alC' op 1alC6 ('here op is operator" e&pr ,1alC' op ,1alC6 1alC32De&pr ,1alC' op ,1alC6D %&a#ples ) e&pr e&pr e&pr e&pr 5E7 FB3 3 8G = 6= . 3 < :i(es )< :i(es . < :i(es )< :i(es E < see output

su#2De&pr 5 E FD echo ,su# < :i(es )) a2'6 b2H0

echo su# is ,a E ,b < 'ill display sum is )- F GH echo su# is @e&pr ,a E ,b@ < :i(es sum is )H$andlin( shell 1ariables The shell has se(eral (aria!les which are automatically set whene(er you login. The (alues o% some o% these (aria!les are stored in names which collecti(ely are called your user en(ironment. Any name de%ined in the user en(ironment, can !e accessed %rom within a shell script. To include the (alue o% a shell (aria!le into the en(ironment you must export it. &pecial shell (aria!les 1reIde%ined shell (aria!les (1arameters to shell scripts" @ There are some (aria!les which are set internally !y the shell and which are a(aila!le to the user@ 9a#e =) I =G =H =< =3 /escription these (aria!les are the positional parameters (1ositional parameters". the name o% the command currently !eing executed (The command name". the num!er o% positional arguments gi(en to this in(ocation o% the shell (parameter count". the exit status o% the last command executed is gi(en as a decimal string. 'hen a command completes success%ully, it returns the exit status o% H (*ero", otherwise it returns a nonI*ero exit status. the process num!er o% this shell I use%ul %or including in %ilenames, to make them uniBue (1IJ o% current shell". the process id o% the last command run in the !ackground (It holds 1IJ o% last !ackground process". the current options supplied to this in(ocation o% the shell. a string containing all the arguments to the shell, starting at =) (All parameters". same as a!o(e, except when Buoted.

==

=>

=I =K =LL

9otes =K and =LL when unBuoted are identical and expand into the arguments. M=KM is a single word, comprising all the arguments to the shell, Noined together with spaces. +or example O) -O . !ecomes M) - .M. M=LLM is identical to the arguments recei(ed !y the shell, the resulting list o% words completely match what was gi(en to the shell. +or example O) -O . !ecomes M) -M M.M Passin( ar(u#ents to the shell &hell scripts can act like standard UNIX commands and take arguments %rom the command line. Arguments are passed %rom the command line into a shell program using the positional parameters =) through to =G. ,ach parameter corresponds to the position o% the argument on the command line. The positional parameter =H re%ers to the command name or name o% the executa!le %ile containing the shell script. 6nly nine command line arguments can !e accessed, !ut you can access more than nine using the shi%t command. All the positional parameters can !e re%erred to using the special parameter =K. This is use%ul when passing %ilenames as arguments. "or e&a#ple) cat printps < This script con(erts A&#II %iles to 1ost&cript < and sends them to the 1ost&cript printer ps) < It uses a local utility Ma-psM a-ps =K P lpr I1ps) printps el#-t&t 1i-re! #s( This processes the three %iles gi(en as arguments to the command printps. %&a#ples o! passin( ar(u#ents to the shell

'rite shell script which will accept 0 num!ers as parameters and display their sum. Also display the contents o% the di%%erent (aria!les in the script. %&a#ple5) * SS5 * sa(e) SS5 para#' para#6 para#3 para# = para#5

* Script to accept 5 nu#bers and display their su#echo the para#eters passed are ) ,'4 ,64 ,34 ,=4 ,5 echo the na#e o! the script is ) ,0 echo the nu#ber o! para#eters passed are ) ,*

su#2@e&pr ,' E ,6 E ,3 E ,= E ,5@ echo :he su# is ) ,su# Why need o! shi!t co##and ? I% more than G parameters are passed to a script, it is not possi!le to re%er to the parameters !eyond the Gth one. This is !ecause shell accepts a single digit %ollowing the dollar sign as a positional parameter de%inition. The shi%t command is used to shi%t the parameters one position to the le%t. 6n the execution o% shi%t command the %irst parameter is o(erwritten !y the second , the second !y third and so on. This implies , that the contents o% the %irst parameter are lost once the shi%t command is executed. %&a#ple o! shi!t ) 'rite a script which will accept di%%erent num!ers and %inds their sum. The num!er o% parameters can (ary. %&a#pleF) *SSF su#20 while I ,* 0(t 0 J do su#2De&pr ,su# E ,'D shi!t done echo su# is ,su# 2ere , the parameter =) is added to the (aria!le sum always . A%ter shi%t , the (alue o% =) will !e lost and the (alue o% =- !ecomes the (alue o% =) and so on. The a!o(e script can also !e written without using the shi%t command as @ %or i in =K do sum5Qexpr =sum F =iQ done Usually only nine command line arguments can !e accessed using positional parameters. The shi%t command gi(es access to command line arguments greater than nine !y shi%ting each o% the arguments. The second argument (=-" !ecomes the %irst (=)", the third (=." !ecomes the second (=-" and so on. This gi(es you access to the tenth command line argument !y making it the ninth. The %irst argument is no longer a(aila!le. &uccessi(e shi%t commands make additional arguments a(aila!le. Note that there is no Munshi%tM command to !ring !ack arguments that are no longer a(aila!le> 7nother %&a#ple o! usin( the shi!t Co##and To successi(ely shi%t the argument that is represented !y each positional parameter@ cat shi!tCde#o

<> !in sh echo Marg)5=) shi%t echo Marg)5=) shi%t echo Marg)5=) shi%t echo Marg)5=)

arg-5=- arg.5=.M arg-5=- arg.5=.M arg-5=- arg.5=.M arg-5=- arg.5=.M

shi!tCde#o one two three !our !i1e si& se1en arg)5one arg-5two arg.5three arg)5two arg-5three arg.5%our arg)5three arg-5%our arg.5%i(e arg)5%our arg-5%i(e arg.5six arg)5%i(e arg-5six arg.5se(en Conditional %&ecution Operators ) KK ( e.g command) RR command-" AA (dou!le pipe" #onditional execution o% commands are use%ul when we want to execute the command !ased on the status o% the pre(ious command, i .e whether the pre(ious command has succeeded or %ailed. This is examined !y the exit status o% each command. +or success o% any command exit status will !e H (*ero" and ) (6ne" i% unsuccess%ul. The operator RR executes the command(s" %ollowing it, i% and only i% the preceding command was success%ully compiled. The PP operator executes the command(s" %ollowing it, i% the preceding command %ailed. %&a#ples o! usin( KK and AA ) ;ls P grep Smydoc.docT RR rm mydoc.doc The a!o(e command will remo(e mydoc.doc i% it exits, otherwise , it will do nothing. ;cat mydoc.doc PP echo S%ile not %oundT The a!o(e command will display the contents o% mydoc.doc i% it exists otherwise %ile not %ound displayed. In case, more than one command is to !e executed or more than one condition need to !e checked simultaneously , then this type o% conditional execution is not help%ul. In such cases the i!0then0eli!0else0!i statement is used.

Control Structures ,(ery Unix command returns a (alue on exit which the shell can interrogate. This (alue is held in the readIonly shell (aria!le =3. A (alue o% H (*ero" signi%ies successU anything other than H (*ero" signi%ies %ailure. :he i! state#ent The i% statement uses the exit status o% the gi(en command and conditionally executes the statements %ollowing. The general syntax is@ i! test then commands Li! condition is trueM else commands Li! condition is !alseM !i then, else and %i are shell reser(ed words and as such are only recogni*ed a%ter a new line or U (semicolon". 7ake sure that you end each i% construct with a %i statement. 9ested i! state#ent ) i! --then --else i! ----!i !i :he eli! state#ent can be used as shorthand !or an else i! state#ent"or e&a#ple) i! --then --eli! ----!i test #ommand @ The Unix system pro(ides test command which in(estigates the exit status o% the pre(ious command and translate the result in the %orm o% success or %ailure, i.e either a H or ). The test command does not produce any output, !ut its exit status can !e passed to the i% statement to check whether the test %ailed or succeeded . $ow to know e&it status o! any co##and ? All commands return the exit status to a preIde%ined &hell Caria!le A3Q . 'hich can !e displayed using the echo command. e.g ; echo =3 I% output o% this is H (Vero" it means the pre(ious command was success%ul and i% output is ) (6ne" it means pre(ious command %ailed. The test command has speci%ic operators to operate on %iles, numeric (alues and strings which are explained !elow @

6perators on Numeric Caria!les used with test command @ IeB @ eBual to Ine @ not eBuals to Igt @ grater than Ilt @ less than Ige @ greater than or eBual to Ile @ less than eBual to %&a#ples) ; a5)-U !5-. ; test =a WeB =! ; echo =3 < :i(es ) (one" as output.(Indicates exit status %alse" 6perators on &tring Caria!les used with test command @ 5 @ eBuality o% strings >5 @ not eBual I* @ *ero length string (i.e string containing *ero character i.e null string". In @ &tring length is non *ero. %&a#ples ) ; name5TAhmadT ; test W* =name null. ; test Wn =name ; test W* S=addressT ; test =name 5 SAliT

# will return the exit status 1 as the string name is not # will return 0 as the string is not null. # will return 0 as the variable has not been defined. # will return 1 as the value of name is not equal to Ali

6perators on %iles used with test command @ I% @ the %ile exists. Is @ the %ile exists and the %ile si*e is non *ero. Id @ directory exists. Ir @ %ile exits and has read permission. Iw @ %ile exists and has write permission. Ix @ %ile exists and has execute permission. %&a#ples) ; test W% Smydoc.docT 0 else 1. ;test Wr Smydoc.docT ; test Wd S=267,T director . # Will check for the file m doc.doc ! if exists! returns # Will check for read "ermission for m doc.doc # Will check for the existence of the users home

9ogical 6perators used with test command @ #om!ining more than one condition is done through the logical ANJ, 68 and N6T operators. Ia @ logical ANJ Io @ logical 68 > @ logical N6T %&a#ple )

; test Wr Smydoc.docT Wa Ww Smydoc.docT # Will check both the read and write "ermission for the file m doc.doc and returns either 0 or 1 de"ending on result. %&a#ple o! usin( an i! construct ) To carry out a conditional action@ i% who P grep Is keith X de( null then echo keith is logged in else echo keith not a(aila!le %i This lists who is currently logged on to the sytem and pipes the output through (rep to search %or the username keith. The Is option causes grep to work silently and any error messages are directed to the %ile de( null instead o% the standard output. I% the command is succes%ul i.e. the username keith is %ound in the list o% users currently logged in then the message keith is logged on is displayed, otherwise the second message is displayed "low o! control state#ents) The Bourne shell pro(ides se(eral %low o% control statements. &elect an item %or %urther in%ormation. :he case state#ent ) The case state#ent case is a %low control construct that pro(ides %or multiI way !ranching !ased on patterns. 1rogram %low is controlled on the !asis o% the wordgi(en. This word is compared with each "attern in order until a match is %ound, at which point the associated command(s" are executed. case word in "attern1" command#s$ UU "attern%" command#s$ UU IIIIIIIIIIIIIIIIIIIIIII IIIIIIIIIIIIIIIIIIIIIII "attern&" command#s$ UU K" de!ault command UU esac 'hen all the commands are executed control is passed to the %irst statement a%ter the esac. ,ach list o% commands must end with a dou!le semiIcolon (UU". A command can !e associated with more than one pattern. 1atterns can !e separated %rom each other !y a P sym!ol.

"or e&a#ple@ case word in "attern1'"attern%" command ... UU 1atterns are checked %or a match in the order in which they appear. A command is always carried out a%ter the %irst instance o% a pattern. The K character can !e used to speci%y a de%ault pattern as the K character is the shell wildcard character. %&a#ple o! usin( the case state#ent) < Jisplay a menu o% options and depending upon the userOs choice , <execute associated command <Jisplay the options to the users clear echo M). Jate and timeM echo echo M-. Jirectory listingM echo echo M.. Users in%ormation M echo echo M/. #urrent JirectoryM echo echo M,nter choice (),-,. or / " @?cM read choice case =choice in )" dateUU -" ls IlUU ." who UU /" pwd UU K" echo wrong choiceUU :he !or state#ent ) :he !or loop notation has the (eneral !or#) !or var in list(of(words do commands done commands is a seBuence o% one or more commands separated !y a newline or U (semicolon". The reser(ed words do and done must !e preceded !y a newline or U (semicolon". &mall loops can !e written on a single line. "or e&a#ple) %or var in listU do commandsU done

%&a#ples o! usin( the !or state#ent ) To take each argument in turn and see i% that person is logged onto the system. cat snooper <> !in sh < see i% a num!er o% people are logged in !or i in =K do i% who P grep Is =i X de( null then echo =i is logged in else echo =i not a(aila!le %i done +or each username gi(en as an argument an i% statement is used to test i% that person is logged on and an appropriate message is then displayed.

:he while and until state#ents ) :he while state#ent has the (eneral !or#) while command(list1 do command(list% done The commands in command(list1 are executedU and i% the exit status o% the last command in that list is H (*ero", the commands in command(list% are executed. The seBuence is repeated as long as the exit status o% command(list1 is H (*ero". :he until state#ent has the (eneral !or#) until command(list1 do command(list% done This is identical in %unction to the while command except that the loop is executed as long as the exit status o% command(list1 is nonI*ero. The exit status o% a while until command is the exit status o% the last command executed in command(list%. I% no such command list is executed, a while until has an exit status o% H (*ero". :he break and continue state#ents ) It is o%ten necessary to handle exception conditions within loops. The statements !reak and continue are used %or this. The !reak command terminates the execution o% the innermost enclosing loop, causing execution to resume a%ter the nearest done statement.

To exit %rom n le(els, use the command@ break n This will cause execution to resume a%ter the done n le(els up. The continue command causes execution to resume at the while, until or %or statement which !egins the loop containing the continue command. You can also speci%y an argument n')* to continue which will cause execution to continue at the n')*th enclosing loop up. %&a#ple o! usin( the break and continue state#ents To prompt %or commands to run@ <> !in sh while echo M1lease enter commandM read response do case M=responseM in OdoneO" break < no more commands UU MM" continue < null command UU K" e(al =response < do the command UU esac done This prompts the user to enter a command. 'hile they enter a command or null string the script continues to run. To stop the command the user enters done at the prompt. So#e #ore e&a#ples !or writin( shell scripts ) *SS7 < To show use o% case statement . echo 'hat kind o% tree !ears acorns? 3 read responce case =responce in Z6o[ZAa[Z$k[" echo =responce is correct UU K" echo &orry, responce is wrong esac *SSN < To show use o% while statement clear echo 'hat is the #apital o% &audi Ara!ia ?3 read answer while test =answer >5 8iyadh do echo No, 'rong please try again. read answer done

echo This is correct. *SSH < ,xample to show use o% until statement < Accept the login name %rom the user clear echo M1lease ,nter the user login name@ ?cM read login\name until who P grep =login\name do sleep .H done echo The user =login\name has logged in *SS'0 <To show use o% i! statement < 8ead three num!ers and display largest clear echo M,nter the %irst num!er @?cM read num) echo M,nter the second num!er @?cM read numecho M,nter the third num!er @?cM read num. i% test =num) Igt =numthen i! test =num) Igt =num. then echo =num) is the largest else echo =num. is the largest !i else i% test =num- Igt =num. then echo =num- is largest else echo =num. is the largest %i !i More on 9OP co##ands)

co#press and unco#press co##and This is like *ip and un*ip in windows. compresses the %iles R decompresses that. %&ecutin( shell co##and durin( lo(in ti#e) .login is s %ile which will !e executed at the time o% logging in. ,dit the %ile to

display a welcome message, current working directory and the date R time. 7ssi(n#ent Proble#s on 9OP S$%LL pro(ra##in(

). 8un all the programs gi(en in the 9a! Notes, and o!ser(e the output %or each program. -. 'rite a shell script that takes a keyword as a command line argument and lists the %ilenames containing the keyword .. 'rite a shell script that takes a command line argument and reports whether it is a directory, or a %ile or a link. /. 'rite a script to %ind the num!er o% su! directories in a gi(en directory. 0. 'rite a shell script to create directories recursi(ely. ,xample@ dir) contains dir)), dir)-, dir). dir)) contains dir))), dir))-, dir)). and so on . ZThe command line input %or the program will !e the nu#ber o! le1els and no- o! directories in each le(el[ ]. write a menu dri(en program that has the %ollowing options. ].). search a gi(en %ile is in the directory or not. ].-. search a gi(en %ile is in the current directory and also recursi(ely in all the su!directories. ]... display the %ull names o% the users logged in.

Anda mungkin juga menyukai