Sie sind auf Seite 1von 34

1of34

LINUX THE

OPENSOURCE ALTERNATIVE

whyenterthroughwindowswhenyouhaveanopendoor

VINEETTULI vtuli77@gmail.com
BasicLinux

2of34

LINUXAnIntroduction WhatisLinux? LinuxisafreelydistributedopensourceoperatingsystemthatresemblesUNIXin many ways. Linux was designed specifically for the PC platform and takes advantage of its design to give users performance comparable to highend Unix workstations. Many big name companies like IBM and Compaq have joined the Linuxbandwagon,offeringsystemspreinstalledwithLinux.RedHat,Corel,Caldera, Apache, Oracle etc. are few among the long list of companies offering Linux distributions or applications. More and more businesses are using Linux as an efficientandeconomicalwaytoruntheirnodes. Linuxisacompletemultitasking,multiuseroperatingsystemthatbehaveslikeUnix intermsofkernelbehaviorandperipheralsupport.Thebestpartisthatitsfree!!You candownloadmostLinuxdistributionsdirectlyofftheweb. TheHistoryBehindLinux In1991,aFinnishcomputersciencestudentLinusTrovaldsacquireda386PCand decidedtostudyoperatingsystemsprogrammingwithit.Hewasdissatisfiedwiththe DOSthatcamewiththesystemandwishedforabetteralternative.Heplayedwitha specialeducationaloperatingsystemcalledMinixthatwasasmallversionofUnix. Butit,too,hadlimitations,includingarestrictivelicense.Afterawhile,hedecidedto writeanewoperatingsystemthatwouldtakebetteradvantageofhishardware.His statedgoalatthetimewasto"writeabetterMinixthanMinix". BecauseofthelonghistoryofUnix,theeleganceofitsbasicdesign,thewidevariety ofsoftwareavailableforit,andhisownfamiliaritywiththesystem,Linusdecidedto writeaversionofUnix.Sincethebasicdesignwaswidelydocumentedandused,he hadplentyofinformationtoworkwith. ThisstartedthedevelopmentofLinux,theoperatingsystemthathasthreatenedthe majorgiantsintheindustry.

BasicLinux

3of34

Linuxvs.OtherOS HeresasmallcomparisonofLinuxwithotherOSthatmayhelpyouunderstand whatmakesitsospecial. LinuxversusWindows98 Windows98ismoreofaPCoperatingsystemandisnotusedtomanagemorethan asmallhomenetwork.ThepopularityofWindows98isbasedonitslowcostand ease of use. As an alternative Linux can be run on a personal PC. Though commercial software applications for Linux are growing, the number of popular applicationsisstillsmallascomparedtoWindows98. LinuxversusWindowsNT Although,bothLinuxandWindowsNTexhibitdifferentstrengthsandweaknesses, LinuxprevailsoverNTintheareaofnetworking.LinuxisalsomuchsmallerthanNT anduseslesssystemresources.InadditionLinuxcrasheslessfrequentlythanNT. Linuxhasbeenknowntoruncontinuouslyonsystemsforseveralmonths,whileNT hasareputationforcrashingoften. LinuxversusUnix Intermsoffeatures,UnixandLinuxarequitesimilar.Howeverthemajordifference betweenUnixandLinuxisthatUnixwasdesignedspecificallyfornetworking.Linux runsperfectlyfineasapersonalUnixsystemandonlargeservers.AlsounlikeUnix, Linuxisfree.Linuxsupportsamuchwiderrangeofhardwareandbecauseofopen sourcemodel,anydriverforcertainhardwarecanbewrittenforLinuxaslongas someonehasthetimetodoso.

BasicLinux

4of34

SystemFeatures Linuxisacompletemultitasking,multiuseroperatingsystemthatbehaveslikeUnix intermsofkernelbehaviorandperipheralsupport.LinuxhasallthefeaturesofUnix, plusseveralrecentextensions.ThesourcecodeforLinux,asalsomostcommon utilitiesareavailableforfree. Linuxallowssharedexecutables,soifmorethanonecopyofaparticularapplication is loaded,all the taskscan share the same memory. Linuxkernel also supports demandpaging,whichmeansthatonlysectionsofaprogramthatarenecessaryare readintoram.Linuxsupportsswapspace.Swapspaceenablespagesofmemoryto be written to a reserved area of a disk and treated as an extension of physical memory. Linuxusesdynamicallysharedlibrariesextensively.Dynamicallysharedlibrariesuse acommonlibrarysectionformanydifferentapplications,effectivelyreducingthesize ofeachapplication.Linuxsupportsalargenumberofdifferentfilesystems,including thosecompatiblewithDOS,WindowsNTandOS/2. Linux is ideallysuitedfornetworking,Webhosting,and applicationdevelopment. Many of the Linux compilers, tools, debuggers and editors are from the Free SoftwareFoundationsGNU(GNUisNotUnix)project. XWindows XWindowsisaGUItoprovideportableGUIapplicationsacrossdifferentplatforms. Xfree86,theversionofXsuppliedwithLinux,supportsseveraldifferentvideocards at different resolutions, offering a high resolution graphical interface. Any X applicationcanberecompiledtorunproperlyunderLinux,andanumberofgames, utilities and addons have been provided as part of the Linux distribution. The Xfree86 system also includes application developmentlibraries,toolsand utilities usingwhichprogrammerscanwriteapplicationsspecificallyforXWindows. DOSinterface Linuxprovidesemulators,whichallowmanyDosandWindowsapplicationstobe executeddirectlyfromwithinLinuxaspartofthedistributionsystem.Linuxallows youto transfer filesseamlesslybetween Linuxfile systemand DOS/Windowsby accessingFATpartitionsonaharddiskdirectly.Thiscapabilitymakesiteasyto movefilesandapplicationsbackandforthbetweenthetwooperatingsystems.

BasicLinux

5of34

FEATURESOFLINUX a) Robust Windows machines needs to be rebooted for very minor oslevel changes. Rebootingamachineforthisisutterlyunacceptable.Linuxwebserverhosting severaldynamicwebsites,handlingwelloveramillionhitsamonthkeepson runningforseveralmonthswithoutevenasinglereboot,despitetheconfiguration changes. b) Secure Linux is very secureas regards to virus attacks.Novirus can attacka Linux machine.Somepoorlywrittennetworkingcodemayallowcertainvulnerabilities butthecollaborativedevelopmenteffortbehindLinuxmeansthatthepatchesare swiftlyreleasedoftenwithinhours. c) Scalable Linuxrunsonalmostallhardwareplatforms,fromawristwatchtoamainframe. Migratingfromalowendx86servertoahigherendserverisveryeasy;just installtheoperatingsystemandcopyallthecode. d) Manageable Linuxisessentiallyselfmaintaining.Turniton,configureitandforgetaboutit. Whenyouneedtomanageitthereareseveralfreedownloadableopensource managementutilitiesavailable.Availabilityofengineersandtechnicalresources isnotanissue,anyonewhocanreadcodecanmanageittoo. e) CostEffective Linuxisfreetouse,freetocopyandfreetoredistribute.Nolicensingisrequired. AlltheutilitiesandapplicationsrequiredtorunontheLinuxplatformarefreely availablefordownloadingfromthenet. f) CanreplaceWindows Linux can be used for presentations, documents, proposals, graphics, spreadsheets, Email, internet surfing etc. For every proprietary, licensed softwarethereexistsapracticablefreeLinuxalternative. g) Easytouse Alltheseadvantageswithdrasticallyimprovedwindowingandgraphicalsystems makeLinuxasimplechoice.LinuxproductsandserviceofferingsfromITmajors like IBM, HP, Compaq, Oracle and Sun have brought Linux on par with commercialandproprietaryplatforms.
BasicLinux

6of34

LINUXCOMPONENTS

Application Programs

Hardware

Kernel Utilities Shell

Kernel TheOSprogramoftheLinuxsystemisthekernel. Itcontrolscomputersresources,allottingthemtodifferentusersandtodifferent tasks. Interactsdirectlywiththehardwaremakingprogramseasytorun. Doesnotdealdirectlywiththeuser,startsupaninteractiveprogramcalledshell tocommunicatewiththeuser. Utilities Theutilitiesorcommandsareacollectionofuserprogramsthatareusedforday todayprocessing. Theseprogramsareinvokedthroughtheshell.

BasicLinux

7of34

ApplicationPrograms Programs for specific applications like DBMS, word processors, language compilersetc. Shell Itactsasthecommandinterpreterforthekernel. Itistheinterfacebetweentheuserandthekernel. FeaturesoftheShell Interactive Processing interactive communication between the user and the system. BackgroundProcessingabilitytorunprogramsinthebackgroundwhileworking intheforeground. I/ORedirectiontakeinputfromonesourceandtakeoutputtotheothersource. Pipesusedtocombinesimplefunctionstoperformcomplexfunctions. ShellScriptsafrequentlyusedsequenceofcommands. ShellVariablesusedtostoreshelldata. ProgrammingConstructscontainsstandardprogramminglanguageconstructs. ShellasCommandInterpreter Shellisaprogram,whichinterpretsthecommandsthataretypedattheterminal, and translates them into commands that the kernel understands. All Linux commandsexistasutilityprograms,mostlywritteninClanguage.Theshellenables ausertogainaccesstoallotherutilitiesandresourcesofthecomputer. Shellprints$onthescreen Userentersthecommand Shellinterpretsthecommand Shellwaitstillthecommandfinishesexecution

BasicLinux

8of34

TypesofFiles IntheLinuxsystemalltheinformationistreatedasafile.Themaintypesoffilesare: Ordinaryfiles Allfilescreatedbytheuseri.e.datafiles,programfiles,executablefiles.Theseare denotedby(). DirectoryFiles For each directory there is a file by the same name, which contains information aboutallfilesinthedirectory.Thesearedenotedby(d). SpecialFiles These are the system filesin Linux. These are basicallyassociated with the I/O devices.ThespecialfilesareoftwotypesBlockRead(b)andCharacterRead(c). The character devices transmit data character by character and block devices transmitdataasablockof512or1024bytes. TypesofUsers SystemAdministrator Isresponsibleforsmoothoperationofthesystem. Isresponsibleforcreatingusers,grantingrightsandaccesses. Hascompletecontroloverthesystem. Identifiedasroot(#). FileOwner Userwhocreatesthefile. Canopen,copy,deleteafile. Hascompleteaccesstothefile. GroupOwner Itisagroupoffileowners. Thefileownerscansharefileswithinagroup. OtherUsers Allusersofthesystemwhoarenotmembersofthegroup.Theseusersdonot needdataorprogramsofthegroup.

BasicLinux

9of34

BASICLINUXCOMMANDS GeneralCommands date id who/whoH printscurrentdateandtime printsusername,groupnameandtheirrespectiveids listdetailsofallusersloggedin listdetailsofownuser

whoami/whoimH man<command> clear

printshelponthecommand typeqtoquit clearsthescreen printscalendarofspecifiedmonth

cal<month><year>

FileCommands ls lsl listallthefilesanddirectories longlistingoffilesanddirectories givesmulticolumnoutputinthefollowingsequence

permissionslinksownergroupsizeinbytescreationdateandtimefilename lsa cat<filename> displayshiddenfilesalso displaycontentsofthefile moves/renamesafile

mv<source><destination> cp<source><destination> rm<filename> rmir<pattern>

copiesafiles removes/deletesafile recursivedeletion

DirectoryCommands

BasicLinux

10of34

pwd cd cd/ cd.. cd<name> mkdir<name> rmdir<name>

printworkingdirectory gobacktohomedirectory gotorootdirectory gotoparentdirectory changedirectory makedirectory remove/deletedirectory

WildcardPatterns * ? [list] stringofnone,oneormorecharacters stringofonesinglecharacter oneoccurrenceofanycharacterinlist

BasicLinux

11of34

LINUXFILESYSTEM TheRedHatLinuxsystemisorganizedasahierarchyofdirectories.Eachdirectory cancontainfiles,aswellasotherdirectories.AtthetopistheRootDirectory,which isrepresentedbyasingleslash(/).Belowthatisasetofcommondirectories, whicharebrieflydescribedbelow.

bin/ dev/ etc/ home/

root/

tmp/ mnt/ sbin/ usr/

user1/user2/user3/

/bin /dev /etc /home /mnt /root /sbin /tmp /usr

containscommonLinuxusercommands. containsfilesrelatedtoallthedevicesinthesystem. containsadministrativeconfigurationfiles. containsdirectoriesassignedtoeachuserwithaloginaccount. providesalocationformountingdevices. representstherootusershomedirectory. containsadministrativecommands. containstemporaryfilesusedbyapplications. containsuserdocumentation,games,graphicalfiles,librariesetc.

BasicLinux

12of34

PIPES&FILTERS Filters are a set of UNIX programs that read some input, perform a simple transformationonit,andwritesomeoutput. Pipesareusedtocombinetheoutputoftwoormorecommandsorfilters.Thepipe isdenotedby(|)symbol. grepfilter Thegrepfilterisapatternsearchingfilter. greppatternfilename grep^patternfilename grepnpatternfilename grepcpatternfilename grepvpatternfilename Displays all lines containing the specified pattern. Displays all lines containing the specified patternatthebeginningoftheline. Displaysthelinenumberswiththeresult. Displaysthetotalcountofallthelinesmatching thepattern. Displays all the lines that do not match the pattern.

sortfilter Thesortfilterisusedforsortingthefilesalphabetically. sortfilename sortffilename sortnfilename sortrfilename ls|sort catfilename|sort wc(wordcount)filter Thewcfilterisusedtocountthenumberoflines,wordsandcharactersinafile. wcfilename wclfilename Displaysthetotallines,wordsandcharactersin thefile. Displaysthetotallinesinafile.
BasicLinux

Sortsthefileinalphabeticalorder. Sortsthefileinalphabeticalorderignoringthe case. Numericsort Reversetheresult Displaysthelistingoffilesinsortedorder. Displaysthecontentsofafileinsortedorder.

13of34

wcwfilename wccfilename headfilter

Displaysthetotalwordsinafile. Displaysthetotalcharactersinafile.

Theheadfilterisusedtodisplaythespecifiednumberoflinesfromthebeginningof thefile. headfilename headnfilename tailfilter Thetailfilterisusedtodisplaythespecifiednumberoflinesfromtheendofthefile. tailfilename tailnfilename morefilter Themorefilterisusedtodisplaythecontentsofafilepagewise. ls|more lsl|more catfilename|more trfilter Thetrfilterisusedtoconvertthefilefromlowercasetouppercaseandviceversa. catfilename|tr[az][AZ] trscharactertosqueeze teefilter Theteefilterisusedtostoretheintermediateresultofacommand. command1|teefilename|command2 Theoutputofcommand1willbestoredinsidethefilespecifiedbyfilename. Convertthefilefromlowercasetouppercase. Removemultipleoccurrencesofthecharacter. Displaysthelistingoffilespagewise. Displaysthelonglistingoffilespagewise. Displaysthecontentsofafilepagewise. Displaysthelast10linesofthefile. Displaysthelastnlinesofthefile. Displaysthefirst10linesofthefile. Displaysthefirstnlinesofthefile.

BasicLinux

14of34

cutfilter Thecutfilterisusedtoextractthespecifiedcharactersorfieldsfromafile. catfilename|cutcn cutddelimiter catfilename|cutfn Cutncharactersfromthefile.ncanbespecified asarangeorcommaseparatedvalues. Specifycolumndelimiter. Cutnfieldsfromthefile.ncanbespecifiedasa rangeorcommaseparatedvalues.

Anexampleofpipesandfilters lsl|grep^d|trs|cutdf9 willdisplaythenamesofdirectoriesonthestandardoutput. lsl|grep^d|trs|cutdf9>filename willwritethenamesofdirectoriesinthefile.

BasicLinux

15of34

THEvi(VISUAL)EDITOR Allvicommandsareenteredincommandmode.Toentercommandmode,pressthe ESC key. Some vi commands cause vi to enter another mode. The i (insert) commandcausesvitoenterinsertmodeafterwhichallkeystrokesareinsertedas text.Toreturntocommandmode,presstheESCkey.The:setshowmodecommand will cause vi to display the current editing mode in the lower right corner of the editingscreen. Beginningyoureditingsession Toeditafile Movingthecursor Beginningofcurrentline Endofcurrentline Leftonecharacter Rightonecharacter Downoneline Uponeline CreatingText Appendtextaftercursor Appendtextafterendofline Inserttextbeforecursor Inserttextatbeginningofline Opennewlineaftercurrentline Opennewlinebeforecurrentline ModifyingText Deletecharacter(aftercursor) Deletecharacter(beforecursor) Deleteword Deleteline Replacecurrentcharacter Undoyourpreviouscommand Copylinetobuffer Putbuffertextaftercursor Putbuffertextbeforecursor

vifilename

0or^ $ h l j k

a A i I o O

x X dw dd r u yy p P

BasicLinux

16of34

Endingyoureditingsessions Quit(nochangesmade) Quitandsavechanges Quitanddiscardchanges UsefulCommands Writechangestooriginalfile Writetospecifiedfile Redafileinafterspecifiedline Displayallsetoptions Displaylinenumbers Displaymodeswhenininsert,appendorreplace

:q :wq :q!

:w :wfilename :rfilename :setall :setnumber :setshowmode

BasicLinux

17of34

FILEPERMISSIONS Therearethreedifferentpermissionspossibleforafile.Theseare: rread wwrite xexecute Toseethepermissionsforaparticularfileordirectoryusethelslcommand.The outputisasfollows: rwrwr 1 viny 50 Sep05 10:10 demo

Thecharacters2to10showthepermissionsforafileordirectory.Thecharacters2 4showthepermissionsfortheuser,characters57showthepermissionsforthe groupandcharacters810showthepermissionsforotherusers. The chmod (changemode)commandisusedtochangethepermissionsforafile. Thegeneralsyntaxis chmodpermissionsfilenames Twoformatsareused: SymbolicDescription: uuser ggroup ootherusers Octalmode: r4 w2 x1 chmod[ugo]+/[rwx]filenames

chmod777filenames

where7=4+2+1i.eread,writeandexecutepermissions.

BasicLinux

18of34

MANAGINGUSERSANDGROUPS CreatingUserAccounts Themaincommandforcreatinganewuseris: useradd<username> passwd<username> Themaincommandoptionswithuseraddarelistedbelow: Option ccomment dhome_dir ggroup Ggrouplist sshell uuser_id Description Provideadescription,generallythepersonsfullname. Setthehomedirectoryfortheaccount. Settheprimarygroupthattheuserwillbein. Add the new user to the supplied commaseperated listofgroups. Specifytheshelltouseforthisaccount. SpecifytheuserIDnumberforthisaccount.

Creatinganewaccountperformsseveralactions:

Readsthe/etc/login.defstoreadthedefaultvaluesforcreatingaccounts. Createsanewuserentryinthe/etc/passwdand/etc/shadowfiles. Createsanewgroupentryin/etc/groupfile. Creates a home directory based on the users name and located within the /homeparentdirectory.

The/etc/passwdfileconsistsofthefollowingentries: loginname:password:userID:primarygroupID:comment:homedirectory:shell The/etc/groupfileconsistsofthefollowingentries: groupname::groupID:listofusers DeletingUserAccounts Theuserdelcommandisusedtodeletetheuser.Ittakesasingleargument,which istheloginnameoftheaccounttodelete.

BasicLinux

19of34

userdel<username> Towipeoutthehomedirectoryalongwiththeaccountuse: userdelr<username> BACKGROUNDPROCESSING Linuxprovidesamethodofrunningtimeconsumingcommandsinthebackground while the user continues working in the foreground. To request a background processingtypetheampersand(&)symbolattheendofthecommandline. #wcfilename& 238 # Thekernelassignstheprocessnumber238totheprocessandreturnsbackthe prompt.Tocheckthebackgroundprocessesuseprocessstatus(ps)command. Toterminateabackgroundprocess,usethekillcommand. #kill<processid> Thekillcommandterminatestherunningprocess. Ifthekillcommandgeneratesanerrorortheprocessdoesntstoprunningusethe command #kill9<processid> Thiswillterminatetheprocess. TAKINGANDRESTORINGBACKUPS Thebackuptaskisdividedintotwomajorparts: Creatinganarchiveoffiles Zippingthearchive CreatingArchives Thetarcommandisusedtocreatearchives.Thegeneralsyntaxoftarcommandis
BasicLinux

20of34

taroptionsfilenamedirectoryname wherefilenameisthenamebywhichthearchivewillbecreatedanddirectoryname isthenamewhichcontainsthefilestobearchived. Optionswithtarcommand: c : createarchive. v : viewfiles. f : filenamebywhichthearchivewillbecreated. w : promptswithayes/nooptionbeforeaddingfilestothe archive. t : listarchivescontents. x : extractfilesfromthearchive.

ZippingFiles Thegzipcommandisusedtozipandunzipfiles. Thesyntaxforzippingfilesis gzip<filenames> andforunzippingfilesis gzipd<zippedfilename> Toviewstatisticsofthezippedfileuse gzipl<zippedfilename> Thezippedfileresultsinafilewitha.gzextension.Theothersupportedextensions are .z gz .Z Z _Z SCHEDULINGTASKS The at facilityisdesignedtorununattendedjobsatspecifictimes.Submittedjobs arespooledinthedirectory /var/spool/at.Thejobsareexecutedusingthecurrent environmentanddirectorythatwasactivewhenthejobwassubmitted.Anyoutputor errormessagesareemailedtotheuserthatsubmittedthejob.

BasicLinux

21of34

Therearetwoaccesscontrolfilesusedtolimitwhichuserscanusethe at facility. Thefile /etc/at.allow containsalistofusersthataregrantedaccess,andthefile /etc/at.denycontainsalistofusersthataredeniedaccess. Thesyntaxofusingatcommandis: #attime[date] at>rmdir/home/viny/demo at>^d Toviewthelistofscheduledjobsusetheatqcommand: #atq 2 20010602 3 20010602

00:51 a 23.52 a

root root

wherethefirstcolumngivesthejobnumber,arepresentstheatqueueandlast columngivesthenameoftheuserwhoscheduledthejob. Toremovethescheduledjobsuse #atrmjobnumber MOUNTINGDEVICESANDFILESYSTEMS Themountcommandisusedtomountadevicetoasystem.Thegeneralsyntaxof themountcommandis: mountdevicetdevicetypeooptionsmountpoint wheredeviceisthenameofthedevicetomountandmountpointisthelocation wherethedevicewillbemounted.Themountpointmustbeadirectoryandmustbe empty.Thedefaultlocationformountingdevicesisthe/mntdirectory.Tounmount usethecommand: umountdevice

FloppyDrives mount/dev/fd0tvfat/mnt/floppy

BasicLinux

22of34

wherevfatisthefilesystemforafloppy. Toformatafloppyuse: fdformat/dev/fd0 Tocreateafilesystemonafloppyuse: mkfs/dev/fd0 mkfsc/dev/fd0checksforbadsectors. CDROM mount/dev/cdromtiso9660/mnt/cdrom whereiso9660isthestandardformatforlayoutofdataonacdrom. HardDiskDrives Toviewstatisticsofpartitionsuse: fdiskl Theharddisk/partitionsarelabeledas /dev/hda1 /dev/hda2etc. Tomountwindows(C:\>)driveonLinuxfollowthefollowingsteps: cd/mnt mkdircdrive mount/dev/hda1/mnt/cdrive cd/mnt/cdrive lstoviewthecontentsofC:\>drive

BasicLinux

23of34

SYSTEMADMINISTRATOR ThemainresponsibilitiesofaSystemAdministratorinclude: Installing,removingterminalsandworkstations. Settingupnewusers. Settingupresources. Grantingrightsandpermissions. Backingandrestoringfiles. Managementofaserver. TheloginnameforasystemadministratorontheLinuxsystemisroot. MethodsofbecomingaSystemAdministrator

Running in single user mode. For going to single user mode type linux
singleattheLILOpromptoreditthe/etc/inittabfile(asexplainedinbooting process). Loginasroot. Ifyouareloggedinasanordinaryuser,type $su Password: # Tologoutfromrootuse^dorexit. BOOTINGANDSHUTDOWNPROCESS

Thelilo(Linuxloader)utilitywritesthebootloadertotheactivepartition. TheliloprocessstartstheLinuxkernel. /etc/lilo.conffileisreadforvariousbootingoptions. Thelilo.conffilecontainsinformationondifferentO/Sbootloadersandboot


sequenceetc.

Aftertheliloprocesstheinitprocessisrun. Theinitprocessiscontrolledbythefile/etc/inittab.

BasicLinux

24of34

Theinitdefaultentryinthe /etc/inittab filedeterminestherunlevelofthe


system.

The inittab also decides what programs are to be run for startup and
maintenancefunctions.

Theinitprocessalsostartsagettyprocessforeachterminalinmultiuser
mode.

Therc(runcommand)scriptshandletasksofbootingthesystem. Thegettyprocessdisplaysaloginmessageoneachterminal. Theloginmessagecontainsthecontentsofthe/etc/issuefile. Thegettyprocesspassestheloginnametotheloginprocess. The/etc/passwdand/etc/shadowfileischeckedtoverifytheuser.


Aftersuccessfullogintheenvironmentalvariablesareinitialized.

Thecontentsof/etc/motd(messageoftheday)filearedisplayed. The $HOME/.bash_profile script is executed to set various user defined


options.

Theshutdowncommand Toshutdownthesystemuse: shutdownoptionstime wherethevariousoptionsare r f h s reboot fastreboot haltthesystem bringtosingleusermode


BasicLinux

25of34

andtimecanbespecifiedin24hoursclockorusenowforimmediateshutdown. SystemCrash Crashisanunwantedsystemstop.Incaseofsystemcrashusethefsck(filesystem check)utilitytorepairthefilesystem.. fsckdevice Torepairthe/dev/hda1deviceuse: fsck/dev/hda1

BasicLinux

26of34

SHELLSCRIPTING Ashellscriptisatextfilecontainingasequenceofcommands.Asimpleshellscript canbeaoneline command,whereasacomplexonecancontainseveral loops, conditional statements, mathematical operations, and control structures etc. Shell scriptsareequivalenttobatchfilesinDOS/Windows. ExecutingShellScripts Shellscriptsarefilesthatyoucanrunasordinarycommands.Therearetwowaysto executeashellscript: The filename is used as an argument to the shell i.e. bash filename. In this methodthefileneednotbeexecutable. Theshellscriptisexecutedbyspecifyingthenameofthefileonthecommand line.Thisrequiresthatthefirstlineoftheshellscriptcontainthenameoftheshell interpreter to be used i.e. #!/bin/bash and that the file must have executable rights.Thefirstlineoftheshellscriptistheonlylinewherethepoundsign(#)is notinterpretedasacomment. #!/bin/sh #TheHelloWorldScript echoHelloWorld Torunthescriptuse: $chmodu+xhello $hello (ifthePATHvariableissettothecurrentdirectory) $shhello or $./hello (ifthePATHvariableisnotsettothecurrentdirectory)

or

Variables Thevariablenamesinshellscriptsarecasesensitiveandaredefinedas:

BasicLinux

27of34

NAME=value Theleftpartisthevariablenameandtherightpartisthevalue.Thevariablescan containtheoutputofacommand. MACHINE=`unamen` HerethevariableMACHINEwillcontainthenameofthecomputer.Thecommand needtoenclosedinthegraveaccentorbackquotes(`).Thevariablescanalso takethevalueofothervariables.Toseethevalueofthevariableadollar($)signis specifiedbeforethevariablename. NAME=Linux MYNAME=$NAME Toacceptvaluesfromtheuseruse: readvarname EnvironmentalVariables Theenvironmentalvariablescontaintheinformationabouttheshellenvironment.To seethevalueofenvironmentalvariablesuse echo$varname USER SHELL HOME PATH UID OSTYPE PS1 displaysusername displaystheshelltheuserisusing displaysusershomedirectory displayspathofexecutables displaysusersidnumberasspecifiedin/etc/passwdfile displaystheoperatingsystemtype

usedtochangetheprompt

BasicLinux

28of34

LocalandGlobalVariables Thevariablesdeclaredontheshellareavailableonlyonthecurrentshell.Theseare knownaslocalvariables.Ifyouloadanewshellthenthatvariablewontbeavailable onthenewshell.Tomakethevariableaccessibleacrossalltheshellsi.e.tomakeit globalusethefollowingsyntax: $exportvariablename Exportingthevariablemakesitaccessibleacrossallthechildshells. ArithmeticEvaluation Allvaluesinshellscriptvariablesaretreatedasalphanumericstrings.Toperform integerarithmetictheexprcommandisused. num=10 result=`expr$num+1` The expr statementneedtobeenclosedingraveaccentsymbolandspacesare requiredonbothsidesofthearithmeticoperator. Thevariousmathematicaloperatorsthatcanbeusedare: */%+<<=>>=!== ProgrammingConstructs ThefordoLoop Thisloopiteratesthroughalistofvalues,executingthebodyoftheloopforeach elementinthelist. forVARinLIST do body done

BasicLinux

29of34

TheifthentestStatement Theifstatementcanbeusedinthefollowingforms: if[expression] then body fi if[expression] then body else body fi if[expression] then body elif[expression] then body else body fi Inthesestatementseachoftheexpressionsistested.Basedontheresultsofthat test,oneoftheactionsthatfollowistaken.Whentheexpressionisevaluatedthe resultiseithera0(i.e.true)ora1(i.e.false). Theifstatementscanalsobewrittenwithoutbracketsas iftestexpression then body fi

BasicLinux

30of34

TestExpressions dfile efile ffile rfile wfile xfile eq ge gt le lt ne a o ThecaseesacStructure Thisstructureissimilartotheswitchstatementinprogramminglanguages. caseVARin Result1) body;; Result2) body;; *) body;; esac ThewhiledoanduntildoLoops whilecondition do body done untilcondition do body done Fileisadirectory Fileexists Fileexistsandisanordinaryfile Fileexistsandisreadable Fileexistsandiswritable Fileexistsandisexecutable Equalityoperator Greaterthanorequaltooperator Greaterthanoperator Lessthanorequaltooperator Lessthanoperator Notequaltooperator Andoperator Oroperator

BasicLinux

31of34

The while loop executes till the condition evaluates to false and the until loop executestilltheconditionevaluatestotrue. PositionalParameters Thepositionalparametersareawayofspecifyingtheargumentsatthecommand line.Thereareatotalofninepositionalparametersnamed$1through$9. Forexample,considertheexecutionofashellscriptnameddemo: $demohellohowareyou On entering this command, each word is automatically stored serially in the positional parameters i.e. $0 will contain demo, $1 will contain hello and so on. Theseareavailabletotheshellscriptasneeded. Thesetcommandisusedtosetthevaluesofthepositionalparametersmanually. Considerthefollowing: Thedatecommanddisplaysthedateinthefollowingformat: SatOct2611:13:43IST2002 Todisplaytheinformationinanyotherformati.e. Sat26Oct2002 Wecanusethefollowingshellscript: set`date` echo$1$3$2$6 Twospecialparametersarealsoavailable: $# $* givesthetotalnumberofpositionalparameters givesthelistofallpositionalparameters.

ShellMetacharacters
BasicLinux

32of34

Theshellmetacharactersarespecialcharacterstowhichspecialsignificancehas beengiven.Thevariousclassificationisasshownbelow: FilenameSubstitution I/ORedirection ProcessExecution QuotingMetacharacters PositionalParameters SpecialCharacters ?*[..][!..] ><>><< ;()&&&|| \`` $1$9 $0$*$@$#$!$$

FilenameSubstitutionMetacharacters * ? [.] [!] Itcanrepresentanycombinationofanynumberofcharacters. Standsforanyonecharacter. Givestheshellachoiceforanyonecharacterfromenclosedlist. Givestheshellachoiceforanyonecharacterexceptthose enclosedinthelist.

I/ORedirectionMetacharacters Thesecharactersspecifyfromwhereinputistobepickedupandwheretheoutputis tobesent. > < >> << Outputredirection Inputredirection Appendtheoutputtothefile Readinputtillthespecifiedcharactersareentered

e.g.:$cat<<demo Thiscommandwillacceptinputfromthestandardinputtilltheworddemois enteredonanewline. ProcessExecutionMetacharacters ; Thisisusedwhenwewanttorunmorethanonecommandatthe$


BasicLinux

33of34

promptinonestroke. $ls;who;pwd () Thiscausesthecommandtobeexecutedinasubshell. $(cdmydir;pwd) /home/demo/mydir $pwd /home/demo & && Itdelegatesagivenprocessexecutiontothebackground. Thisisusedwhenwewantthesecondcommandtobeexecuted onlyifthefirstcommandsucceeds. Thisisusedwhenwewantthesecondcommandtobeexecuted onlyifthefirstcommandfails.

||

QuotingMetacharacters \ `` Ittakesawaythespecialmeaningattachedtoanymetacharacter. Thesinglequotesprinteveryenclosedcharacterasis. Thedoublequotesallowsustousethemetacharacters. Thebackquotesreplacethecommandwithitsoutput. $name=demo $echoMynameis$name Mynameisdemo $echoMynameis$name Mynameis$name PositionalParameters

BasicLinux

34of34

$1$9

Holdsthevaluesofcommandlinearguments.

SpecialCharacters $$ $? $! $# $0 $* $@ ProcessIDofcurrentshell Exitstatusoflastexecutedcommand ProcessIDoflastbackgroundprocess Totalnumberofpositionalparameters Nameofcommandbeingexecuted Listofshellarguments Similarto$*butyieldseachargumentseparately

Ifwerunashellscriptdemoasfollows: $demof1f2f3 wheref1f2f3arenamesofthreefiles cat$*istreatedascatf1f2f3 whereas cat$@istreatedascatf1f2f3

EndofDocument

BasicLinux

Das könnte Ihnen auch gefallen