Tải bản đầy đủ - 0 (trang)
Chapter 1. Introduction to UNIX Shells

Chapter 1. Introduction to UNIX Shells

Tải bản đầy đủ - 0trang

Chapter1.IntroductiontoUNIXShells

1.1DefinitionandFunction

1.2SystemStartupandtheLoginShell

1.3ProcessesandtheShell

1.4TheEnvironmentandInheritance

1.5ExecutingCommandsfromScripts



1.1DefinitionandFunction

Theshellisaspecialprogramusedasaninterfacebetweentheuserand

theheartoftheUNIXoperatingsystem,aprogramcalledthekernel,as

showninFigure1.1.Thekernelisloadedintomemoryatboot-uptime

andmanagesthesystemuntilshutdown.Itcreatesandcontrols

processes,andmanagesmemory,filesystems,communications,andso

forth.Allotherprograms,includingshellprograms,resideoutonthedisk.

Thekernelloadsthoseprogramsintomemory,executesthem,and

cleansupthesystemwhentheyterminate.Theshellisautilityprogram

thatstartsupwhenyoulogon.Itallowsuserstointeractwiththekernel



byinterpretingcommandsthataretypedeitheratthecommandlineorin

ascriptfile.

Figure1.1.Thekernel,theshell,andyou.



Whenyoulogon,aninteractiveshellstartsupandpromptsyouforinput.

Afteryoutypeacommand,itistheresponsibilityoftheshellto(a)parse

thecommandline;(b)handlewildcards,redirection,pipes,andjob

control;and(c)searchforthecommand,andiffound,executethat

command.WhenyoufirstlearnUNIX,youspendmostofyourtime

executingcommandsfromtheprompt.Youusetheshellinteractively.

Ifyoutypethesamesetofcommandsonaregularbasis,youmaywant

toautomatethosetasks.Thiscanbedonebyputtingthecommandsina

file,calledascriptfile,andthenexecutingthefile.Ashellscriptismuch

likeabatchfile:ItisalistofUNIXcommandstypedintoafile,andthen

thefileisexecuted.Moresophisticatedscriptscontainprogramming

constructsformakingdecisions,looping,filetesting,andsoforth.Writing

scriptsnotonlyrequireslearningprogrammingconstructsand

techniques,butassumesthatyouhaveagoodunderstandingofUNIX

utilitiesandhowtheywork.Therearesomeutilities,suchasgrep,sed,

andawk,thatareextremelypowerfultoolsusedinscriptsforthe

manipulationofcommandoutputandfiles.Afteryouhavebecome

familiarwiththesetoolsandtheprogrammingconstructsforyour



particularshell,youwillbereadytostartwritingusefulscripts.When

executingcommandsfromwithinascript,youareusingtheshellasa

programminglanguage.



1.1.1TheThreeMajorUNIXShells

ThethreeprominentandsupportedshellsonmostUNIXsystemsarethe

Bourneshell(AT&Tshell),theCshell(Berkeleyshell),andtheKornshell

(supersetoftheBourneshell).Allthreeofthesebehaveprettymuchthe

samewaywhenrunninginteractively,buthavesomedifferencesin

syntaxandefficiencywhenusedasscriptinglanguages.

TheBourneshellisthestandardUNIXshell,andisusedtoadminister

thesystem.Mostofthesystemadministrationscripts,suchasthercstart

andstopscriptsandshutdownareBourneshellscripts,andwhenin

singleusermode,thisistheshellcommonlyusedbytheadministrator

whenrunningasroot.ThisshellwaswrittenatAT&Tandisknownfor

beingconcise,compact,andfast.ThedefaultBourneshellpromptisthe

dollarsign($).

TheCshellwasdevelopedatBerkeleyandaddedanumberoffeatures,

suchascommandlinehistory,aliasing,built-inarithmetic,filename

completion,andjobcontrol.TheCshellhasbeenfavoredoverthe

Bourneshellbyusersrunningtheshellinteractively,butadministrators

prefertheBourneshellforscripting,becauseBourneshellscriptsare

simplerandfasterthanthesamescriptswritteninCshell.ThedefaultC

shellpromptisthepercentsign(%).

TheKornshellisasupersetoftheBourneshellwrittenbyDavidKornat

AT&T.Anumberoffeatureswereaddedtothisshellaboveandbeyond

theenhancementsoftheCshell.Kornshellfeaturesincludeaneditable

history,aliases,functions,regularexpressionwildcards,built-in

arithmetic,jobcontrol,coprocessing,andspecialdebuggingfeatures.

TheBourneshellisalmostcompletelyupward-compatiblewiththeKorn

shell,soolderBourneshellprogramswillrunfineinthisshell.The

defaultKornshellpromptisthedollarsign($).



1.1.2TheLinuxShells



Althoughoftencalled"Linux"shells,BashandTCshellsarefreely

availableandcanbecompiledonanyUNIXsystem;infact,theshells

arenowbundledwithSolaris8andSun'sUNIXoperatingsystem.But

whenyouinstallLinux,youwillhaveaccesstotheGNUshellsandtools,

andnotthestandardUNIXshellsandtools.AlthoughLinuxsupportsa

numberofshells,theBourneAgainshell(bash)andtheTCshell(tcsh)

arebyfarthemostpopular.TheZshellisanotherLinuxshellthat

incorporatesanumberoffeaturesfromtheBourneAgainshell,theTC

shell,andtheKornshell.ThePublicDomainKornshell(pdksh)aKorn

shellclone,isalsoavailable,andforafeeyoucangetAT&T'sKornshell,

nottomentionahostofotherunknownsmallershells.

ToseewhatshellsareavailableunderyourversionofLinux,lookinthe

file,/etc/shell.

Tochangetooneoftheshellslistedin/etc/shell,typethechshcommand

andthenameoftheshell.Forexample,tochangepermanentlytotheTC

shell,usethechshcommand.Attheprompt,type:



chsh/bin/tcsh

1.1.3HistoryoftheShell

Thefirstsignificant,standardUNIXshellwasintroducedinV7(seventh

editionofAT&T)UNIXinlate1979,andwasnamedafteritscreator,

StephenBourne.TheBourneshellasaprogramminglanguageisbased

onalanguagecalledAlgol,andwasprimarilyusedtoautomatesystem

administrationtasks.Althoughpopularforitssimplicityandspeed,it

lacksmanyofthefeaturesforinteractiveuse,suchashistory,aliasing,

andjobcontrol.Enterbash,theBourneAgainshell,whichwas

developedbyBrianFoxoftheFreeSoftwareFoundationundertheGNU

copyrightlicenseandisthedefaultshellfortheverypopularLinux

operatingsystem.ItwasintendedtoconformtotheIEEEPOSIX

P1003.2/ISO9945.2ShellandToolsstandard.Bashalsooffersanumber

ofnewfeatures(bothattheinteractiveandprogramminglevel)missingin

theoriginalBourneshell(yetBourneshellscriptswillstillrun

unmodified).ItalsoincorporatesthemostusefulfeaturesofboththeC

shellandKornshell.It'sbig.TheimprovementsoverBourneshellare:



commandlinehistoryandediting,directorystacks,jobcontrol,functions,

aliases,arrays,integerarithmetic(inanybasefrom2to64),andKorn

shellfeatures,suchasextendedmetacharacters,selectloopsfor

creatingmenus,theletcommand,etc.

TheCshell,developedattheUniversityofCaliforniaatBerkeleyinthe

late1970s,wasreleasedaspartof2BSDUNIX.Theshell,written

primarilybyBillJoy,offeredanumberofadditionalfeaturesnotprovided

inthestandardBourneshell.TheCshellisbasedontheCprogramming

language,andwhenusedasaprogramminglanguage,itsharesasimilar

syntax.Italsooffersenhancementsforinteractiveuse,suchas

commandlinehistory,aliases,andjobcontrol.Becausetheshellwas

designedonalargemachineandanumberofadditionalfeatureswere

added,theCshellhasatendencytobeslowonsmallmachinesand

sluggishevenonlargemachineswhencomparedtotheBourneshell.

TheTCshellisanexpandedversionoftheCshell.Someofthenew

featuresare:commandlineediting(emacsandvi),scrollingthehistory

list,advancedfilename,variable,andcommandcompletion,spelling

correction,schedulingjobs,automaticlockingandlogout,timestampsin

thehistorylist,etc.It'salsobig.

WithboththeBourneshellandtheCshellavailable,theUNIXusernow

hadachoice,andconflictsaroseoverwhichwasthebettershell.David

Korn,fromAT&T,inventedtheKornshellinthemid-1980s.Itwas

releasedin1986andofficiallybecamepartoftheSVR4distributionof

UNIXin1988.TheKornshell,reallyasupersetoftheBourneshell,runs

notonlyonUNIXsystems,butalsoonOS/2,VMS,andDOS.Itprovides

upward-compatibilitywiththeBourneshell,addsmanyofthepopular

featuresoftheCshell,andisfastandefficient.TheKornshellhasgone

throughanumberofrevisions.ThemostwidelyusedversionoftheKorn

shellisthe1988version,althoughthe1993versionisgainingpopularity.

LinuxusersmayfindtheyarerunningthefreeversionoftheKornshell,

calledThePublicDomainKornshell,orsimplypdksh,acloneofDavid

Korn's1988shell.Itisfreeandportableandcurrentlyworkisunderway

tomakeitfullycompatiblewithitsnamesake,Kornshell,andtomakeit

POSIXcompliant.AlsoavailableistheZshell(zsh),anotherKornshell

clonewithTCshellfeatures,writtenbyPaulFalsted,andfreelyavailable

atanumberofWebsites.



1.1.4UsesoftheShell

Oneofthemajorfunctionsofashellistointerpretcommandsenteredat

thecommandlinepromptwhenrunninginteractively.Theshellparses

thecommandline,breakingitintowords(calledtokens),separatedby

whitespace,whichconsistsoftabs,spaces,oranewline.Ifthewords

containspecialmetacharacters,theshellevaluatesthem.Theshell

handlesfileI/Oandbackgroundprocessing.Afterthecommandlinehas

beenprocessed,theshellsearchesforthecommandandstartsits

execution.

Anotherimportantfunctionoftheshellistocustomizetheuser's

environment,normallydoneinshellinitializationfiles.Thesefilescontain

definitionsforsettingterminalkeysandwindowcharacteristics;setting

variablesthatdefinethesearchpath,permissions,prompts,andthe

terminaltype;andsettingvariablesthatarerequiredforspecific

applicationssuchaswindows,text-processingprograms,andlibrariesfor

programminglanguages.TheKornshellandCshellalsoprovidefurther

customizationwiththeadditionofhistoryandaliases,built-invariables

settoprotecttheuserfromclobberingfilesorinadvertentlyloggingout,

andtonotifytheuserwhenajobhascompleted.

Theshellcanalsobeusedasaninterpretedprogramminglanguage.

Shellprograms,alsocalledscripts,consistofcommandslistedinafile.

Theprogramsarecreatedinaneditor(althoughon-linescriptingis

permitted).TheyconsistofUNIXcommandsinterspersedwith

fundamentalprogrammingconstructssuchasvariableassignment,

conditionaltests,andloops.Youdonothavetocompileshellscripts.The

shellinterpretseachlineofthescriptasifithadbeenenteredfromthe

keyboard.Becausetheshellisresponsibleforinterpretingcommands,it

isnecessaryfortheusertohaveanunderstandingofwhatthose

commandsare.SeeAppendixAforalistofusefulcommands.



1.1.5ResponsibilitiesoftheShell

Theshellisultimatelyresponsibleformakingsurethatanycommands

typedatthepromptgetproperlyexecuted.Includedinthose

responsibilitiesare:



1. Readinginputandparsingthecommandline.

Evaluatingspecialcharacters.

Settinguppipes,redirection,andbackgroundprocessing.

Handlingsignals.

Settingupprogramsforexecution.

Eachofthesetopicsisdiscussedindetailasitpertainstoaparticular

shell.



1.2SystemStartupandtheLoginShell

Whenyoustartupyoursystem,thefirstprocessiscalledinit.Each

processhasaprocessidentificationnumberassociatedwithit,calledthe

PID.Sinceinitisthefirstprocess,itsPIDis1.Theinitprocessinitializes

thesystemandthenstartsanotherprocesstoopenterminallinesandset

upthestandardinput(stdin),standardoutput(stdout),andstandarderror

(stderr),whichareallassociatedwiththeterminal.Thestandardinput

normallycomesfromthekeyboard;thestandardoutputandstandard

errorgotothescreen.Atthispoint,aloginpromptwouldappearonyour

terminal.

Afteryoutypeyourloginname,youwillbepromptedforapassword.The

/bin/loginprogramthenverifiesyouridentitybycheckingthefirstfieldin

thepasswdfile.Ifyourusernameisthere,thenextstepistorunthe

passwordyoutypedthroughanencryptionprogramtodetermineifitis

indeedthecorrectpassword.Onceyourpasswordisverified,thelogin

programsetsupaninitialenvironmentconsistingofvariablesthatdefine

theworkingenvironmentthatwillbepassedontotheshell.TheHOME,

SHELL,USER,andLOGNAMEvariablesareassignedvaluesextracted

frominformationinthepasswdfile.TheHOMEvariableisassignedyour

homedirectory;theSHELLvariableisassignedthenameofthelogin

shell,whichisthelastentryinthepasswdfile.TheUSERand/or

LOGNAMEvariablesareassignedyourloginname.Asearchpath

variableissetsothatcommonlyusedutilitiesmaybefoundinspecified



directories.Whenloginhasfinished,itwillexecutetheprogramfoundin

thelastentryofthepasswdfile.Normally,thisprogramisashell.Ifthe

lastentryinthepasswdfileis/bin/csh,theCshellprogramisexecuted.If

thelastentryinthepasswdfileis/bin/shorisnull,theBourneshellstarts

up.Ifthelastentryis/bin/ksh,theKornshellisexecuted.Thisshellis

calledtheloginshell.

Aftertheshellstartsup,itchecksforanysystemwideinitializationfiles

setupbythesystemadministratorandthenchecksyourhomedirectory

toseeifthereareanyshell-specificinitializationfilesthere.Ifanyof

thesefilesexist,theyareexecuted.Theinitializationfilesareusedto

furthercustomizetheuserenvironment.Afterthecommandsinthose

fileshavebeenexecuted,apromptappearsonthescreen.Theshellis

nowwaitingforyourinput.



1.2.1ParsingtheCommandLine

Whenyoutypeacommandattheprompt,theshellreadsalineofinput

andparsesthecommandline,breakingthelineintowords,calledtokens.

Tokensareseparatedbyspacesandtabsandthecommandlineis

terminatedbyanewline.[1]Theshellthencheckstoseewhetherthefirst

wordisabuilt-incommandoranexecutableprogramlocatedsomewhere

outondisk.Ifitisbuilt-in,theshellwillexecutethecommandinternally.

Otherwise,theshellwillsearchthedirectorieslistedinthepathvariable

tofindoutwheretheprogramresides.Ifthecommandisfound,theshell

willforkanewprocessandthenexecutetheprogram.Theshellwill

sleep(orwait)untiltheprogramfinishesexecutionandthen,if

necessary,willreportthestatusoftheexitingprogram.Apromptwill

appearandthewholeprocesswillstartagain.Theorderofprocessing

thecommandlineisasfollows:

1. Historysubstitutionisperformed(ifapplicable).

Commandlineisbrokenupintotokens,orwords.

Historyisupdated(ifapplicable).

Quotesareprocessed.



Aliassubstitutionandfunctionsaredefined(ifapplicable).

Redirection,background,andpipesaresetup.

Variablesubstitution($user,$name,etc.)isperformed.

Commandsubstitution(echofortodayis'date')isperformed.

Filenamesubstitution,calledglobbing(catabc.??,rm*.c,etc.)is

performed.

Programexecution.



1.2.2TypesofCommands

Whenacommandisexecuted,itisanalias,afunction,abuilt-in

command,oranexecutableprogramondisk.Aliasesareabbreviations

(nicknames)forexistingcommandsandapplytotheC,TC,Bash,and

Kornshells.FunctionsapplytotheBourne(introducedwithAT&TSystem

V,Release2.0),Bash,andKornshells.Theyaregroupsofcommands

organizedasseparateroutines.Aliasesandfunctionsaredefinedwithin

theshell'smemory.Built-incommandsareinternalroutinesintheshell,

andexecutableprogramsresideondisk.Theshellusesthepathvariable

tolocatetheexecutableprogramsondiskandforksachildprocess

beforethecommandcanbeexecuted.Thistakestime.Whentheshellis

readytoexecutethecommand,itevaluatescommandtypesinthe

followingorder:[2]

1. Aliases

Keywords

Functions(bash)

Built-incommands

Executableprograms

If,forexample,thecommandisxyztheshellwillchecktoseeifxyzisan



alias.Ifnot,isitabuilt-incommandorafunction?Ifneitherofthose,it

mustbeanexecutablecommandresidingonthedisk.Theshellthen

mustsearchthepathforthecommand.



1.3ProcessesandtheShell

Aprocessisaprograminexecutionandcanbeidentifiedbyitsunique

PID(processidentification)number.Thekernelcontrolsandmanages

processes.Aprocessconsistsoftheexecutableprogram,itsdataand

stack,programandstackpointer,registers,andalltheinformation

neededfortheprogramtorun.Whenyoustarttheshell,itisaprocess.

Theshellbelongstoaprocessgroupidentifiedbythegroup'sPID.Only

oneprocessgrouphascontroloftheterminalatatimeandissaidtobe

runningintheforeground.Whenyoulogon,yourshellisincontrolofthe

terminalandwaitsforyoutotypeacommandattheprompt.

Theshellcanspawnotherprocesses.Infact,whenyouentera

commandatthepromptorfromashellscript,theshellhasthe

responsibilityoffindingthecommandeitherinitsinternalcode(built-in)

oroutonthediskandthenarrangingforthecommandtobeexecuted.

Thisisdonewithcallstothekernel,calledsystemcalls.Asystemcallis

arequestforkernelservicesandistheonlywayaprocesscanaccess

thesystem'shardware.Thereareanumberofsystemcallsthatallow

processestobecreated,executed,andterminated.(Theshellprovides

otherservicesfromthekernelwhenitperformsredirectionandpiping,

commandsubstitution,andtheexecutionofusercommands.)

Thesystemcallsusedbytheshelltocausenewprocessestorunare

discussedinthefollowingsections.SeeFigure1.2.

Figure1.2.Theshellandcommandexecution.



1.3.1WhatProcessesAreRunning?

ThepsCommand.Thepscommandwithitsmanyoptionsdisplaysalist

oftheprocessescurrentlyrunninginanumberofformats.Example1.1

showsallprocessesthatarerunningbyusersonaLinuxsystem.(See

AppendixAforpsanditsoptions.)



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 1. Introduction to UNIX Shells

Tải bản đầy đủ ngay(0 tr)

×