You are on page 1of 198

StudyGuidefor

LinuxSystemAdministration1
LabworkforLPI101
version0.2

releasedundertheGFDLbyLinuxIT

LinuxITTechnicalTrainingCentre

___________________________________________________________________

Copyright (c) 2005 LinuxIT.


Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.2
or any later version published by the Free Software Foundation;
with the Invariant Sections being History, Acknowledgements,Funding with
the Front-Cover Texts being released under the GFDL by LinuxIT.

seefulllicenseagreementonp.180

____________________________________________________________________________________________________________

Pageiii

LinuxITTechnicalTrainingCentre

___________________________________________________________________

Introduction:
Acknowledgments
TheoriginalmaterialwasmadeavailablebyLinuxIT'stechnicaltrainingcentrewww.linuxit.com.Many
thankstoAndrewMeredithforsuggestingtheideainthefirstplace.Aspecialthankstoallthestudentswho
havehelpeddilutethetechnicalaspectsofLinuxadministrationthroughtheirmanyquestions,thishasledto
theinclusionofmoreillustrationsattemptingtointroduceconceptsinauserfriendlyway.Finally,many
thankstoPaulMcEneryforthetechnicaladviceandforstartingoffsomeofthemostdifficultchapterssuch
astheonescoveringtheXserver(101),modems(102)andtheLinuxkernel(102).
Themanualisavailableonlineathttp://savannah.nongnu.org/projects/lpimanuals.Thankyoutothe
SavannahVolunteersforassessingtheprojectandprovidinguswiththeWebspace.

Funding
DevelopmentofthesematerialshavepartiallybeenfundedbyUNDPAPDIPInternationalOpenSource
NetworkandInternationalDevelopmentResearchCentreCanada.

Trademarks
LinuxistheregisteredtrademarkofLinusTorvaldsintheU.S.andothercountries.
RedHatLinuxandRedHatEnterpriseLinuxareregisteredtrademarksofRedHat,Inc.
MandrivaLinuxisaregisteredtrademarkofMandrivaInc.
SUSE(SUSEisatrademarkofSUSELINUXProductsGmbH,aNovellbusiness)
____________________________________________________________________________________________________________

Pageiv

LinuxITTechnicalTrainingCentre

___________________________________________________________________
UNIXisaregisteredtrademarkoftheOpenGroup.

History
Firstrelease(version0.0)October2003.ReviewedbyAdrianThomasset.
RevisedJanuary2004afterreviewbyAndrewMeredith.
November2004.Sectiononexpansioncardsaddedin'HardwareConfiguration'chapterbyAdrian
Thomasset
December2004.IndexandmappedobjectivesaddedbyAdrianThomasset.
January2005.Glossaryofterms,commandandfilereviewaddedatendofchaptersbyAdrianThomasset
June2005.AddednewentriesinlinewithrecommendationsfromSerNetfortheLATMprocess,byAndrew
MeredithwithadditionaltextsuppliedbyAndrewDMarshallandreviewbyAdrianThomasset.Sectionon
DebiantoolssuppliedbyDuncanThomson.
August2005."LinuxSystemAdministration1LabworkLPI101version0.2"hasbeenawardedtheLATM
statusbySerNet.

DramatisPersoni
AdrianThomasset
AndrewMeredith
AndrewDMarshall
DuncanThomson

<adriant@linuxit.com>
<andrew@anvil.org>
<admarshall@gmail.com>
<thomci0@paisley.ac.uk>

http://www.linuxit.com/
http://www.anvil.org/
http://h0lug.sourceforge.net/
http://www.paisley.ac.uk/

Goals
Thismanualsprimaryaimistoprovideexplanations,examplesandexercisesforthosepreparingforthe
LinuxProfessionalInstitute(LPI)CertificationProgramme1(LPIC1),Exam101.
Threecoresourcesofcriteriaguidethismanualtoitsprimarygoals:
TheLPI'sExam101"Objectives".
ItsLPIApprovedTrainingMaterials(LATM)criteria.
TheLinuxDocumentationProject(LDPorTLDP)AuthorGuide(AG).
TheLPI'sExam101ObjectivesandLATMcriteriaaresummarizedbelow.TheObjectivesarealsoonlineat:
http://www.lpi.org/en/obj_101.html
TheLDPAuthorGuide[http://www.tldp.org/LDP/LDPAuthorGuide/]providesaconsistent,comprehensive
setofguidelinesforthosewantingtopublishHOWTOs,TutorialsandManualsviatheworld'slargest
GNU/Linuxdocumentationsystem,theLDP.
Thismanualadoptsasitssecondprimeobjective,onequalfootingwithitsfirst,theLDPAuthorGuide's
challengetoprospectiveLDPauthors,"tomassagealloftherawdataintoareadable,entertainingand
understandablewhole."[LDPAG,4.1.WritingtheText]

____________________________________________________________________________________________________________

Pagev

LinuxITTechnicalTrainingCentre

___________________________________________________________________

IntendedTrainingSchedules
ThecontenthereinisdesignedtoaccompanypracticalcoursespreparingfortheLPI101examoftheLPIC1
programme.Whilethismaterialwasgenerallystructuredtoworkwithacourseof2432hoursinconsecutive
8hoursessions,itismodularizedtoalsoworkforshorterorlongersessions,consecutiveorotherwise.

IntendedAudience&Prerequisites
Thismanual'smaterialassumesitsuserswillalreadyhave:
Extensiveexperience(severalyears)usingIntelx86computers,includingastrongknowledgeof

hardwarecomponentsandtheirinteractionwithbasicoperatingsystem(OS)components.
Ageneralknowledgeofcomputingandnetworkingbasicssuchasbinaryandhexadecimalmaths,

commonunitsofmeasure(bytes,KBvsKb,Mhz,etc),filesystemstructures,EthernetandInternet
networkingoperationsandhardware,etc.
MorethanthreecumulativemonthsofpracticalexperienceusingaGNU/Linux,BSDorUnixOS,loggedin

andworkingatthecommandline(inatextterminalorconsole)eitherlocallyorremotely.
Thosewithlessexperience,however,shouldnotbediscouragedfromusingthismanual,if(andonlyif)they
arewillingtospendextratimecatchingupontheprerequisitebackgroundskillsandknowledge;a
challengingtask,butnotanimpossibleone.
Furtherreferencesandexamplesareprovidedforthevarioususesofcommands,aswellasexercisesand
accompanyinganswersdemonstratingexamlikeproblemsolving.Allareoptionalwiththosemost
recommendedeitherdiscussedorreferencedinthemanual'sbody.

TheLPICertificationProgram
TherearecurrentlytwoLPIcertificationlevels.ThefirstlevelLPIC1isgrantedafterpassingbothexamsLPI
101andLPI102.SimilarlypassingtheLPI201andLPI202examswillgrantthesecondlevelcertification
LPIC2.
TherearenocertificationprerequisitesforLPI101and102.HowevertheexamsforLPIC2canonlybe
attemptedonceLPIC1hasbeenobtained.

InstructorNotice
Therearenoinstructornoteswiththismanual.Thefollowingissuesmustbeconsidered.
TheexercisesinthesectionsManagingDevicesandTheLinuxFilesystembothassumethatanew
partitioncanbecreated.Makesureduringtheinstallationthatalargeextendedpartitionwithatleast100MB
freespaceisavailableafterallthepartitionshavebeencreated.
ThefollowingRPMpackagesareneededfortheexercises:
rpmbuild
____________________________________________________________________________________________________________

Pagevi

LinuxITTechnicalTrainingCentre

___________________________________________________________________
sharutils

NoGuarantee
Themanualcomeswithnoguaranteeatall.

Resources
www.lpi.org
www.linuxpraxis.de
www.lpiforums.com
www.tldp.org
www.fsf.org
www.linuxit.com

Notations
Commandsandfilenameswillappearinthetextinbold.
The<>symbolsareusedtoindicateanonoptionalargument.
The[]symbolsareusedtoindicateanoptionalargument
Commandsthatcanbetypeddirectlyintheshellarehighlightedasbelow

command
or

command

____________________________________________________________________________________________________________

Pagevii

LinuxITTechnicalTrainingCentre

Contents
__________________________________________________

INTRODUCTION:........................................................................................................................... III
Acknowledgments.................................................................................................................................... iii
Funding.................................................................................................................................................... iii
Trademarks............................................................................................................................................. iii
History..................................................................................................................................................... iv
DramatisPersoni..................................................................................................................................... iv
Goals....................................................................................................................................................... iv
IntendedTrainingSchedules.................................................................................................................. iv
IntendedAudience&Prerequisites........................................................................................................... v
TheLPICertificationProgram.................................................................................................................. v
InstructorNotice....................................................................................................................................... v
NoGuarantee........................................................................................................................................... v
Resources................................................................................................................................................ v
Notations................................................................................................................................................. vi

INSTALLATION............................................................................................................................... 1
1.TheInstallationCD.............................................................................................................................. 2
2.LocalInstallations................................................................................................................................. 3
3.NetworkInstallation.............................................................................................................................. 3
4.Rescuedisk.......................................................................................................................................... 4
5.PartitioningSchemes............................................................................................................................ 5
6.EasyDualBooting............................................................................................................................... 6
7.ExercisesandSummary....................................................................................................................... 8

HARDWARECONFIGURATION...................................................................................................10
1.ResourceAllocation............................................................................................................................ 11
2.PCExpansionCards.......................................................................................................................... 12
3.USBSupport...................................................................................................................................... 13
4.SCSIDevices..................................................................................................................................... 14
5.Networkcards.................................................................................................................................... 15
6.Settingupmodems............................................................................................................................. 16
7.PrinterConfiguration........................................................................................................................... 21
8.SoundCards...................................................................................................................................... 22
9.ExercisesandSummary..................................................................................................................... 24

MANAGINGDEVICES................................................................................................................... 27
1.DisksandPartitions............................................................................................................................ 28
2.PartitioningTools:............................................................................................................................... 30
3.Bootloaders........................................................................................................................................ 31
4.Manageddevices............................................................................................................................... 33
5.Quotas................................................................................................................................................ 35
6.ExercisesandSummary..................................................................................................................... 36

THELINUXFILESYSTEM............................................................................................................. 39
1.TheFilesystemStructure.................................................................................................................... 40
2.FormattingandFileSystemConsistency...........................................................................................42
3.MonitoringDiskUsage....................................................................................................................... 45
4.FilePermissionsandAttributes.......................................................................................................... 46
5.ExercisesandSummary..................................................................................................................... 52

THECOMMANDLINE................................................................................................................... 56
____________________________________________________________________________________________________________

Page8

LinuxITTechnicalTrainingCentre

Contents
__________________________________________________
1.Theinteractiveshell............................................................................................................................ 57
2.Variables............................................................................................................................................ 58
3.Input,Output,Redirection................................................................................................................... 59
4.MetacharactersandQuotes............................................................................................................... 62
5.TheCommandHistory........................................................................................................................ 63
6.OtherCommands............................................................................................................................... 64
7.ExerciseandSummary...................................................................................................................... 67

FILEMANAGEMENT.................................................................................................................... 71
1.Movingaroundthefilesystem............................................................................................................. 72
2.FindingFilesandDirectories.............................................................................................................. 72
3.Handlingdirectories............................................................................................................................ 74
4.Usingcpandmv................................................................................................................................. 74
5.HardLinksandSymbolicLinks........................................................................................................... 75
7.Touchinganddding........................................................................................................................... 76
8.ExercisesandSummary..................................................................................................................... 78

PROCESSMANAGEMENT........................................................................................................... 81
1.Viewingrunningprocesses................................................................................................................. 82
2.ModifyingProcesses.......................................................................................................................... 83
3.Processesandtheshell..................................................................................................................... 85
4.ExercisesandSummary..................................................................................................................... 87

TEXTPROCESSING..................................................................................................................... 89
1.cattheSwissArmyKnife.................................................................................................................... 90
2.Simpletools........................................................................................................................................ 91
3.Manipulatingtext................................................................................................................................ 93
4.ExercisesandSummary..................................................................................................................... 96

SOFTWAREINSTALLATION........................................................................................................98
1.Introduction......................................................................................................................................... 99
2.StaticandSharedLibraries............................................................................................................ 100
3.SourceDistributionInstallation......................................................................................................... 104
4.TheRedHatPackageManagerRPM..............................................................................................107
5.DebianPackageManagement......................................................................................................... 112
6.TheAlienTool.................................................................................................................................. 116
7.ExercisesandSummary................................................................................................................... 117

ADVANCEDTEXTMANIPULATION...........................................................................................120
1.RegularExpressions........................................................................................................................ 121
2.Thegrepfamily................................................................................................................................. 121
3.Workingwithgrep............................................................................................................................. 122
4.egrepandfgrep................................................................................................................................ 122
5.TheStreamEditorsed................................................................................................................... 123
6.ExercisesandSummary................................................................................................................... 125

USINGVI..................................................................................................................................... 127
1.viModes........................................................................................................................................... 128
2.TextItems......................................................................................................................................... 128
3.InsertingText.................................................................................................................................... 129
4.CutandPaste................................................................................................................................... 129
5.CopyPaste....................................................................................................................................... 130
6.SearchandReplace........................................................................................................................ 130
7.UndoandRedo................................................................................................................................ 130
____________________________________________________________________________________________________________

Page9

LinuxITTechnicalTrainingCentre

Contents
__________________________________________________
8.RunningaShellCommand............................................................................................................... 131
9.SaveandQuit................................................................................................................................... 131
10.ExercisesandSummary................................................................................................................. 132

THEXENVIRONMENT............................................................................................................... 134
1.Introduction....................................................................................................................................... 135
2.ConfiguringX11R6........................................................................................................................... 136
3.ControllingXclients.......................................................................................................................... 138
4.StartingX.......................................................................................................................................... 139
5.TheDisplayManager....................................................................................................................... 140
6.TroubleshootingXClients................................................................................................................. 144
7.ChoosingaWindowManager........................................................................................................... 144
9.ExercisesandSummary................................................................................................................... 145

ANSWERSTOREVISIONQUESTIONS.....................................................................................149
LPI101OBJECTIVES................................................................................................................. 151
Topic101:Hardware&Architecture..................................................................................................... 151
Topic102:LinuxInstallation&PackageManagement.........................................................................153
Topic103:GNU&UnixCommands..................................................................................................... 155
Topic104:Devices,LinuxFilesystems,FilesystemHierarchyStandard..............................................158
Topic110:TheXWindowSystem........................................................................................................ 161

GNUFREEDOCUMENTATIONLICENSE..................................................................................163
INDEX.......................................................................................................................................... 168

____________________________________________________________________________________________________________

Page10

LinuxITTechnicalTrainingCentre

Installation

__________________________________________________

Installation
Prerequisites
None

Goals
UnderstandthelayoutofatypicalLinuxinstallationCD
Performdifferenttypesofinstallations
Createasimplepartitionscheme(seealsop.32)

Contents
INSTALLATION............................................................................................................................... 1
1.TheInstallationCD.............................................................................................................................. 2
2.LocalInstallations................................................................................................................................. 3
3.NetworkInstallation.............................................................................................................................. 3
4.Rescuedisk.......................................................................................................................................... 4
5.PartitioningSchemes............................................................................................................................ 5
6.EasyDualBooting............................................................................................................................... 6
7.ExercisesandSummary....................................................................................................................... 8

____________________________________________________________________________________________________________

Page1

LinuxITTechnicalTrainingCentre

Installation

__________________________________________________

1.TheInstallationCD
ThevariousLinuxdistributionshavedifferentnamesforthedirectoriesontheinstallationCD.Thegeneric
structureoftheCDROMisasfollows:
GenericInstallationCDlayout

cdrom
dosutils

packages

images

packages:Thisdirectorycontainstheprecompiledpackages.Herearetheassociatednamesforthemain
distrubutions:
debian:dist
mandrake:Mandrake
redhat:RedHat
suse:suse
Initiallyallthesoftwareinstalledonthesystemcomesfromthesepackagedfiles.Seethesectiononpackage
managersonp.120formoredetails.
images:Thisdirectorycontainsvariousimages.Thesearespecialflatfilesoftencontainingdirectory
structures.Aninitialramdisk(initrd)isanexampleofanimagefile.Therearedifferenttypesofimages
necessaryto:
boottheinstallationprocess
provideadditionalkernelmodules
rescuethesystem
Someofthesefilescanbecopiedtoafloppydiskwhentheinstallationisstartedusingfloppiesratherthan
theCDROM.TheLinuxtoolusedtodothisisdd.Thereisatoolcalledrawritewhichdoesthesameunder
DOS.
Theimageisaspecialfilewhichmaycontainsubdirectories(muchlikeanarchivefile).
Imagefilestructure

DIR1

Imagefile

DIR2

____________________________________________________________________________________________________________

Page2

LinuxITTechnicalTrainingCentre

Installation

__________________________________________________
Animagefilecanbemountedonaloopdevice.IftheimagefilenameiscalledImagethenthefollowing
commandwillallowonetoviewthecontentofthisfileinthe/mnt/floppydirectory:
mount -o loop /path/to/Image /mnt/floppy

dosutils:thisdirectorycontainsDOStoolswhichmaybeusedtoprepareaLinuxinstallationsuchasthe
rawrite.exetoolmentionedabove.AnothertoolisthefipsutilitywhichnondestructivelypartionsaC:\drive
intwoprovidedtheunderlyingfilesystemtypeisFATandnotNTFS.

2.LocalInstallations
Theeasiestandmostcommontypeofinstallationisalocalinstallation.MostdistributionsareaCDisoimage
withanautomaticinstallationscript.OnmachineswithnoCDROMhardwareitisstillpossibletostartan
installationfromafloppy.

CDROMinstallation
ChangethesettingsintheBIOSforthecomputertobootfromCD.Theinstallationismenudrivenandallows
foradvancedandbasicconfiguration.

FloppyInstallation
Ifforsomereasonyoudon'tbootusingtheCDROMyouwillneedtocreateafloppyinstallationimage.This
canhappeniftheCDisnotbootableoryouhavedownloadedanonisoimageofthedistribution.
Makingabootableinstallationdisk
ddif=/path/to/<image_name>of=/dev/fd0 onalinuxbox
rawrite.exe
underWindows(notNT)
ForRedHatdistributionstheinstallationimagesareintheimagesdirectory.Thebasicimageisboot.img.
Otherimagesaremorespecialisedlikebootnet.imgorpcmcia.img.
InaSusedistributionthefloppyimageisinthedisksdirectoryandtheimageiscalledbootdisk.

3.NetworkInstallation
ForaRedHatinstallationthisisonlyaspecialisedfloppyinstallation.Makeabootablefloppyusingthe
bootnet.imgimage:

dd/mnt/cdrom/images/bootnet.imgof=/dev/fd0

Thefirstpartoftheinstallationistextbasedandwillallowyoutosetupthekeyboardandthenetwork
parametersneeded.TherestoftheinstallationcanbedoneviaFTP,NFSorHTTP.Originallyprotocolsthat
____________________________________________________________________________________________________________

Page3

LinuxITTechnicalTrainingCentre

Installation

__________________________________________________
allowedafullmount(NFS)wouldalsoallowtheinstalltobedoneingraphicalmode,whilefileretrieval
protocols(FTPHTTP)wouldonlyallowtextmode.Withmostmoderndistributionsthisisnolongerthecase.
AlsonoticethatmostmoderndistributionsoffernetworkinstallationsdirectlyfromtheCD(e.gMandrakedisk
2willstartanetworktypeinstallationorFedoraCorecantaketheparameteraskmethodatboottime).

4.Rescuedisk
IfaLinuxsystemiscorruptitispossibletobootthecomputerusingarescuedisk.Thisisasmallversionof
Linuxthatwillmountaminimalvirtualfilesystemintomemory.
TheLinuxoperatingsystemrunsentirelyinRAM.TheaimistoaccesstherootfilesystemonthePChard
drive.Mostrescuediskscandeterminethisautomatically.Assumingtherootfilesystemwasfoundonthe
firstlogicalpartitionofthecomputer'sfirstIDEdisk(/dev/hda5),therescuediskscriptcanthenmountthis
resourceonasubdirectoryofthefilesysteminRAM,say/mnt/system.
Changingperspectives
Inthissituationwehavetworootfilesystemsasdepictedbelow.Tousetherootfilesystemonthehard
driveasourtopdirectoryweneedtochangeourperspective(changeroot).Thechroottooldoesjustthat:

chroot /mnt/sysimage

Rescuemode

RAMkernel
initrd

rootfilesysteminRAMrootfilesystemonPCharddrive

Gettingstarted
____________________________________________________________________________________________________________

Page4

LinuxITTechnicalTrainingCentre

Installation

__________________________________________________
OldMethod:
1.
2.
3.
4.

Makeabootablefloppyusingtheboot.imgimagefile:ddif=boot.imgof=/dev/fd0
Copytherescue.imgimagefiletoasecondfloppy:ddif=rescue.imgof=/dev/fd0
Bootthesystemusingwiththeboot.imgdiskette
AttheLILOprompttype"linuxrescue".Youshouldseesomethinglike
Insertrootfilesystemdisk:

5. Inserttherescue.imgdisketteandpressenter
6. Thebootprocesswillcontinueuntilyougetashellprompt
7. Youmaystillneedtodeterminewheretherootfilesystemisontheharddrive(notcovered)
NewMethod:
1.InserttheLinuxinstallationdisk(Suse,RedHat,Mandrake...)
2.Attheprompttypelinuxrescue
3.Followtheinstructions.
4.Theinstuctionshouldsaywheretherootfilesystemismounted
5.Iftherootfilesystemismountedon/mnt/sysimagethenenterthefollowingcommand

5.PartitioningSchemes
Toaccessresourcesonaharddrivetheoperatingsystemusesamechanismcalled'mounting'.ForUNIX
typeoperatingsystemsthisinvolvesattachingadisktoanydirectorywhichisthencalledamountpoint.
Thefigurebelowshowsapossiblepartitioningscheme.Heremanyresources(notonlylocaldisksand
partitions,butpossiblynetworkshares,CDROMs,etc)areattachedonvariousmountpoints
Totheuserthefilesystemlayoutissimplyatreeofdirectoriesandsubdirectories.
Formingatreelikefilesystemstructure
Therootofthetreestructureiscalledrootandisrepresentedbyaforwardslash/.Therootmountpointis
alsothefirstdirectoryonwhichtheoperatingsystemwillattachadiskorresource,alsocalledtheroot
device.
Oncetherootismountedthedirectoriesandsubdirectoriespresentontherootdevicecanbeusedasfurther
mountpointsforotherdevices,formingasuccessionofdirectoriesorderedlikeatree.
Theprocessismadepossibleasfollows:
1.Thebootloaderwillloadakerneltellingitwheretherootdeviceis(alsosee"BootingLinux"LPI
102)
2.Theotherdirectoriesaremountedfollowinginstructionsfromthe/etc/fstabfile(seep.37)

____________________________________________________________________________________________________________

Page5

LinuxITTechnicalTrainingCentre

Installation

__________________________________________________

Mountpointsonthefilesystem

CreatingtheDiskLayout
WheninstallingLinuxonehastocreateapartitionscheme.Thisisaparticularstageoftheinstallation
processandisdonemostoftenwithaGUItoolsuchasYastorDiskDruid.Thesetoolsallowonetodothree
things:

createpartitionsofagivensize
selectthefilesystemtype(seep.49)
assignamountpointforeachpartition.

Someinstallationshavean'expertmode'whereitispossibletousefdisk(seep.33)tocreatethepartitions
only.
Aminimalpartitionschemeinvolvesonerootdeviceandanotherpartitionforswapping.Therearenorules
whencreatingadisklayoutbutonegenerallytakesintoaccountthefunctionofthecomputer(desktop,mail
server,etc).

TheSWAPpartition
Whencreatingapartitionschemeonealsohastomakedecisionsabouttheamountofswapspaceneeded.
Onceagain,therearenorules.Theamountofswapspaceneededdependsofthetypeofapplicationsthat
willrunonthePC(desktop,server,3Drendering,etc.).Howeverasaruleofthumb,fora2.4kernelwithan
averageamountofRAM(e.glessthan256MB)onewillgenerallycreateaswapspacetwiceaslargeasthe
amountofRAM.Witholder2.2kernelsonewouldcreateaswappartitionofthesamesizeastheamountof
RAM.
Swappingisgenerallydoneusingapartition.Inthepartitiontablethehexadecimalvalueforaswappartition
is82.
____________________________________________________________________________________________________________

Page6

LinuxITTechnicalTrainingCentre

Installation

__________________________________________________

NOTICE
Unlikepartitionsusedforstoringdataaswappartitionisnevermounted.Onealsodoesn'tassignamount
pointforsuchpartitions.TocreateaSWAPspaceduringtheinstallationonsimplyselectsthe'filesystem
type'labelled'SWAP'.
OncethesystemisrunninginformationabouttheSWAPpartitionsisavailablein/proc/swaps
OnecanalsocreateSWAPspaceareasusingfilesratherthanpartitions(seeLPI201).Thisisoftenusedfor
emergenciesonceasystemisrunningandnotduringtheinstallation.

6.EasyDualBooting
(Thissectionisnotforexampurposesandcanbeleftoutcompletely).
IfWindows9x/2kisalreadyinstalledonthesystemtheinstallationsetupwillautomaticallyconfigureLILOfor
dualbooting.

Preinstallation:
Beforealteringthesystemyoushouldrunadefragmentationprogramoverthewholedisk.Thiswillmake
surethatalltheblocksusedbytheWindowsoperatingsystemarerearrangedatthebeginningofthedisk.
Next,usingPartitionMagicorfips,partitiontheC:\driveintwo.TheWindowsprogramsarelocatedatthe
beginningoftheharddiskinthefirstpartition.ThesecondpartitionmustbelargeenoughtoholdaLinux
installation.
Notice:TheaverageamountofspaceneededforaLinuxdistributionis4GB.

StartingtheinstallationfromDOS:
FornonNTsystemsrestartyourcomputerinDOScommandmode.IfyouareinstallingRedHatthenyou
canrunE:\DOSUTILS\AUTOBOOT.BAT.Thiswillstarttheinstallationprogram.Similarlyifyouare
installingSuseyoucanrunE:\setup.exeunderDOS.

TheharddrivefromaWindows'perspective:
WhenrunningWindowstheOSwillonlyseetheFATandNTFSfilesystems.Therestofthediskwhere
Linuxisinstalledwillbeinaccessible.

TheharddrivefromaLinuxpointofview:

____________________________________________________________________________________________________________

Page7

LinuxITTechnicalTrainingCentre

Installation

__________________________________________________
WhenrunningLinuxtheWindowspartitionshouldbecalled/dev/hda1(sinceit'sthefirstpartitiononthefirst
physicaldisk).Bydefaultthispartitionisnotmounted.Youcanmakeadirectory/dosor/mnt/dosand
mountthispartition.ThediskpartitioncorrespondingtoC:\isthenaccessible.

____________________________________________________________________________________________________________

Page8

LinuxITTechnicalTrainingCentre

Installation

__________________________________________________

7.ExercisesandSummary
ReviewQuestions(answersp.165)
YesorNo
1.TherawritetoolrunsunderLinuxandisusedtocopyanimagefileontoafloppydisk
_____

2.Whendevisinganewpartitionschemeonanemptydiskanydiskpartitioncanbechosenastheroot
device
_____
Glossary
Term

Description

virtualfilesystem

afilesystemisadatastructurethatallowsdataonadisktobeorganisedand
accessedbytheuser.Howevertotheuserdataissimplylocatedinaseriesof
directoriesandsubdirectories.Thesedirectoriesformatreestructurewithatop
directorycalledtherootandnoted"/".Thisstructureisalsocalledthe'virtual
filesystem'becauseonedoesn'tneedtoknowanythingaboutthedisklayoutor
partitioningschemeinordertouseit.Thisisdifferenttothesituationwhenusinga
DOSbasedsystem;thereifthediskhasfourpartitionsalltheuserswillneedtoknow
thatdatacanbeineitherC:\,D:\,E:\orF:\and,inthisexample,thatthefirstCDROM
istheG:\device

mountpoint

adirectorywhereapartitionisattachedinordertomakethedeviceavailabletothe
system

partitioningscheme actionperformedduringtheinstallationtofixthenumberofpartitionsandmountpoints
inordertocreateastandard'virtualfilesystem'onwhichsoftwareisinstalled.The
standardwhichdecideswheresoftwarecomponentsareinstalledorwhereuserhome
directoriesarekeptiscalledthefilesystemhierarchystandard(FHS)andshould
influenceourchoiceswheninstallingLinux(e.gmostsoftwareisinstalledinthe/usr
directory,thereforealwaysmakesurethatthisdirectoryisonafairlylargepartition,at
least2GBinmostcases)
rescuemode

actionofrunningaLinuxoperatingsystementirelyinRAMtogetherwithasmallroot
filesystemcontainingenoughtoolstoaccesstheharddrive.Thisisgenerallystarted
withaninstallationCD

root(/)

thetopdirectorywhereafirstpartitionisattached.Eitherallthedirectoriesand
subdirectoriesneededcanbefoundonthispartitionorcertainsubdirectoriesofroot
canbeusedasmountpointstoattachfurtherpartitions(thisdependsonthepartition
schemechosenduringtheinstallation!)

Commands
Command

Description

chroot

changeintoadirectoryandconsiderthatdirectoryastheroot(/).Bydefaultchroot
triestoruntheBashshell/bin/bash,butitispossibletospecifyanyothercommand
(see'chrootedservers'inLPI202)

____________________________________________________________________________________________________________

Page9

LinuxITTechnicalTrainingCentre

Installation

__________________________________________________
dd

toolusedtocopyfilesaswellasportionsofadevice(e.gharddrive,CDROMor
floppy).AninstallationCDcontainsfilescalled'imagefiles'whicharecopiesof
installationordriverdisksthatcanbecopiedbackontoafloppy

fips.exe

autilityfoundonmostLinuxdistributionCDsthatisusedtoresizeaFATpartitionin
ordertomakespaceforadualbootWindows/Linuxsystem

rawrite

aDOSequivalentofdd

Exercises
1.DoalocalCDinstallation.Thefollowingpointsoutlineasuggestedstrategy.TheOPTIONALpointsshould
beattemptedonlybyadvancedusersfamiliarwithpackagemanagementandthevieditor.
(i)InstallationType:chooseCustom
(ii)DiskPartitioningSetup:PartitionthediskmanuallywithDiskDruid:
Thisisasuggestionforapartitioningschemeusingabout3GBofharddiskspace.Ifyouhavemore
spaceavailablethenmake/usrlargerandconsiderinstallingmorepackagesthanthosesuggestedin
step(iv)
IMPORTANT:Leaveafreepartitionofatleast100MB.Wewillneedthislater!!
/boot
/ 250M
/usr
/home
/tmp
/var
SWAP

20M
2300M
50M
100M
150M
128MNoticethatSWAPisafilesystemtypeandthatnomountpointisdefinedseep.6

(iii)(OPTIONAL)InstallLILOon/dev/hda2ornotatall.Inallcasesdonotusethesuggested/dev/hda,
whichistheMBR.
Wedeliberatelydon'twanttheinstallationtobootproperly.Thebootloaderwillbefixedinstep2(i)
inrescuemode.
(iv)Packagestoinstall:(thenamesmayvaryfromonedistributiontoanother)
XWindowSystem+GNOMEdesktopenvironmentORKDEdesktopenvironment
Editors
GraphicalInternet
SoftwareDevelopment[Thisisimportant,wewillneedthistocompilepackageslater]
(v)Dontcreateabootablefloppy
2.(OPTIONAL)Rescuethesystem:
(i)RebootwiththeinstallationCDROM.Attheprompttype:
linuxrescue
(ii)Readalltheinstructionsuntilyougettoaprompt.Usethechrootcommandassuggested.
____________________________________________________________________________________________________________

Page10

LinuxITTechnicalTrainingCentre

Installation

__________________________________________________
(iii)Youfirstneedtoinstallthelilopackage.Edit/etc/lilo.conf(usevi).Youshouldhave
boot=/dev/fd0
prompt
linear
timeout=50
image=/boot/vmlinuz<kernelversion>
label=linux
readonly
root=/dev/<rootpartition>
(v)Run/sbin/lilo.Ifanerroroccursyoumayhavetoreplacelinearbylba32dependingonyourdisk.

____________________________________________________________________________________________________________

Page11

LinuxITTechnicalTrainingCentre

HardwareConfiguration

________________________________________________

HardwareConfiguration
Prerequisites
None

Goals
Understandhardwareresourceallocation(IRQs,I/OportsandDMA)
Overviewhardwaredevicessuchasexpansioncards,USBandSCSIdevices
Detectionofnetworkinterfacesandprinters(noconfiguration)
Understandbasicconfigurationstepsformodemsandsoundcards

Contents
HARDWARECONFIGURATION..............................................................................................10
1.ResourceAllocation...................................................................................................................... 11
2.PCExpansionCards..................................................................................................................... 12
3.USBSupport................................................................................................................................. 13
4.SCSIDevices................................................................................................................................ 14
5.Networkcards............................................................................................................................... 15
6.Settingupmodems........................................................................................................................ 16
7.PrinterConfiguration...................................................................................................................... 21
8.SoundCards................................................................................................................................. 22
9.ExercisesandSummary............................................................................................................... 24

________________________________________________________________________________________________________

Page12

LinuxITTechnicalTrainingCentre

HardwareConfiguration

________________________________________________

1.ResourceAllocation
ToallowperipheralsanddevicesonthePCtocommunicatedirectlywithsystemresources,inparticular
theCPU,thesystemallocatesresourcessuchaslinesandchannelsforeachdevice.Theseresources
areInterruptRequestLines(IRQ),Input/OutputaddressesandDirectMemoryAccesschannels(DMA).

IRQs:TheInterruptRequestLinesallowdevicestorequestCPUtime.TheCPUwillstopitscurrent
activityandprocesstheinstructionssentbythedevice.IRQsrangefrom0to15.
I/Oaddress:Theserepresentspecificaddressesinthesystemsmemorymap.TheCPUwillthen
communicatewiththedevicebyreadingandwritingtomemoryatthespecifiedaddress.
DMA:CertaindevicescanaccessthesystemsmemorythroughaDMAchannel,allowingthemtowrite
andprocessdatawithoutaccessingtheCPU.Thiscanenhanceperformance.

ListingAllocatedResources
Thekernelkeepsinformationrelatedtoallocatedresourcesinthe/procdirectory.Therelevantfilesare:

/proc/dma
/proc/interrupts
/proc/ioports
/proc/pci

Allocatedresourcescanalsobelistedusingtoolssuchaslspcianddmesg:
lspci:listschipsetinformationofallattachedPCIcomponents.ListsI/OandIRQsettingswiththevflag.
Alsonoticetheb(BUScentric)optionwhichshowsallocationsassignedbytheBIOSratherthanthe
kernel.
dmesg.Continuouslydisplayskernelmessages.Italsodisplaysthekernelmessagesloggedatboottime
duringthekernelstage.Atthisstagethekernelscansallthehardwareonthesystemandcan
automaticallyallocatemodules(drivers)forgivenchipsets.Thesemessagesarealsoavailablein
/var/log/dmesg.

TypicalResources
Device
/dev/ttyS0
/dev/ttyS1
/dev/lp0

I/Oport
0x03f8
0x02f8
0x378

IRQ
4
3
7

________________________________________________________________________________________________________

Page13

LinuxITTechnicalTrainingCentre

HardwareConfiguration

________________________________________________
/dev/lp1
soundcard

0x278
0x220

ManualResourseAllocation

NOTICE:
Thisisaverycommonexample,howeversincekernelmodulesareonlydiscussedinLPI102somemay
finditdifficult.Youmayskipthisexampleandgotosection2

Example:configuringtwoethernetcards

1.Forstaticallycompiledmodules,parameterscanbepassedtothekernelatboottime.Atypical
exampleiswhentwoethernetcardsarepresentandonlythefirstoneisdetected.Thefollowinglinetells
thekernelthat:
thereisanethernetcardusingIRQ10andI/O0x300
thereisanotherethernetcardusingIRQ9andI/O0x340

ether=10,0x300,eth0

ether=9,0x340,eth1

YoutypethislineattheLILO/GRUBboot:prompt,orelse,aswiththeRAMsettingsbefore,edit
/etc/lilo.conf(useanappend=statement)or/etc/grub.conf.
Noticethattheether=statementisagenerickernelcommandsimilartoroot=,mem=orinit=.
Alsonoticethatyouneednotspecifyanyinformationabouttheethernetcard(Intel,Netgear...)

2.Fordynamicallycompiledmodules,IRQandI/Oaddresssettingscanbedefinedusing
/etc/modules.conf(or/etc/conf.modules).Assumingthatintheaboveexamplebothcardswhereusing
thee100.okernelmodule,then/etc/modules.confwouldcontainthefollowing:

aliaseth0e100
aliaseth1e100
optionseth0io=0x300irq=10
optionseth1io=0x340irq=9

________________________________________________________________________________________________________

Page14

LinuxITTechnicalTrainingCentre

HardwareConfiguration

________________________________________________

2.PCExpansionCards
ISAandPCIarethemostcommontypesofexpansioncards.Withthelatest2.4kernelthereisverylittle
tobedoneinordertoconfigurethese.InthecaseofISAbuseshowever,andonlywithearlierkernels,it
wasnecessarytoscantheISAbusinordertodetectexistingexpansioncards(sound,ethernet,etc).
TheisapnptoolspackageprovidedthepnpdumptoolwhichscannedtheISAbusfor'PlugandPlay'(pnp)
devices.TheoutputwouldcontainthechipsetofthecardtogetherwithI/Oport,DMAandIRQsettings.
Thisoutputwouldberedirectedto/etc/isapnp.confwherechangescouldbemadeifneeded.Atboot
timetheisapnptoolwouldreadisapnp.confandwouldconfiguretheseISAPnPdevices.
Sincekernel2.4PnPinitialisationissupportedthroughakernelmodulecalledisapnp.o

3.USBSupport
TheUniversalSerialBus(USB)isacommunicationarchitecturedesignedtoconnectdevicestoaPC.
Thesedevicesaredividedintofourclasses:
DisplayDevices
CommunicationDevices
AudioDevices
MassStorageDevices
HumanInterfaceDevices(HID)
ThedevicesarepluggedintoaUSBportwhichisdrivenbyaUSBcontroller.SupportforUSBcontrollers
ispresentintheLinuxkernelsinceversion2.2.7(TheLinuxUSBsubsystemHOWTO)
HostControlers
Thereare3typesofUSBhostcontrollers:
HostControlerKernelModule
OHCI(Compaq)
usbohci.o
UHCI(Intel)
usbuhci.o
EHCI(USBv2.0)
ehcihdc.o
OnceaUSBdeviceispluggedintoaPCwecanlistthedeviceswithlsusb:

lsusb
Bus001Device001:ID0000:0000
Bus001Device002:ID04a9:1055Canon,Inc.

Hotplugging

________________________________________________________________________________________________________

Page15

LinuxITTechnicalTrainingCentre

HardwareConfiguration

________________________________________________
Hotplugisamechanismusedtokeepthestateoftheoperatingsystemupdatedwhenpluggable
hardwaredevicesareaddedorremoved.Inmostcasesthekernelsignalsaneventbypassing
parameterstothescript/sbin/hotplug.
Thishotplugscriptrunsallthescriptsin/etc/hotplug.d(thedefaultisdefault.hotplug)whichinturn
startstheappropriateagentlistedin/etc/hotplug.Thenamesoftheagentscorrespondtodifferent
attachmenttypessuchasieee1394,net,pci,scsiandusb.
ThefollowinglogdescribeswhathappenswhenaUSBcameraisinitialised:
Stage1:USBkernelmodulesidentifyUSBeventandvendor/productID:
13:26:19kernel:hub.c:newUSBdevice00:07.21,assignedaddress5
13:26:19kernel:usb.c:USBdevice5(vend/prod0x4a9/0x3058)isnotclaimedbyanyactivedriver.

Stage2:Theeventargumentsarepassedtodefault.hotplug
13:26:19default.hotplug[10507]:arguments(usb)env(DEVFS=/proc/bus/usbOLDPWD=/
PATH=/bin:/sbin:/usr/sbin:/usr/binACTION=addPWD=/etc/hotplugHOME=/SHLVL=2
DEVICE=/proc/bus/usb/001/005PRODUCT=4a9/3058/1TYPE=255/255/255DEBUG=yes_=/bin/env)

Stage3:Theusb.agentassociatestheproducttoausbcam(usingusb.usermap)
13:26:19default.hotplug[10507]:invoke/etc/hotplug/usb.agent()
13:26:23usb.agent[10507]:SetupusbcamforUSBproduct4a9/3058/1
13:26:23usb.agent[10507]:ModulesetupusbcamforUSBproduct4a9/3058/1
13:26:38devlabel:devlabelservicestarted/restarted
FromthiswecanseethatStep1involvesthekernelmodulesandStep23involvethehotplug
mechanism.OnecanalsoseethatthecorrectUSBmapmustbeavailableinordertofullyinitialisethe
device.

Theusbmgrtool
OnDebiansystemsanalternativetohotplugisprovidedwiththeusbmgrpackage.Themainfilesare:
/usr/sbin/usbmgr
ThedaemonthatlistensforUSBrelatedevents
/usr/sbin/dump_usbdev
TooltolistUSBdevices(similartolsusb)
/etc/usbmgr/usbmgr.conf Configurationfilecontainingvendor/productIDs

4.SCSIDevices
TypesofSCSIdevices
TherearetwotypesofSCSIinterfaces:
________________________________________________________________________________________________________

Page16

LinuxITTechnicalTrainingCentre

HardwareConfiguration

________________________________________________
an8bitinterfacewithabusthatsupports8devices,thisincludesthecontroller,sothereisonlyspace
for7blockdevices(tapes,disks,etc)
a16bitinterface(WIDE)withabusthatsupports16devicesincludingthecontroller,sotherecanonly
be15blockdevices.
SCSIdevicesareuniquelyidentifiedusingasetof3numberscalledtheSCSIID:
a.theSCSIchannel
b.thedeviceIDnumber
c.thelogicalunitnumberLUN

TheSCSIChannel
EachSCSIadaptersupportsonedatachannelonwhichtoattachSCSIdevices(disc,CDROM,etc)
Thesechannelsarenumberedfrom0onwards.

DeviceIDnumber
EachdeviceisassignedauniqueIDnumberthatcanbesetusingjumpersonthedisk.TheIDsrange
from0to7for8bitcontrollersandfrom0to15for16bitcontrollers.
LogicalUnits
TheLogicalUnitNumber(LUN)isusedtodifferentiatebetweendeviceswithinaSCSItargetnumber.This
isused,forexample,toindicateaparticularpartitionwithinadiskdriveoraparticulartapedrivewithina
multidrivetaperobot.Itisnotseensooftenthesedaysashostadaptersarenowlesscostlyandcan
accommodatemoretargetsperbus.

HardwareDetection
Alldetecteddevicesarelistedinthe/proc/scsi/scsifile.TheexamplebelowisfromtheSCSI2.4
HOWTO
/proc/scsi/scsi
Attacheddevices:
Host: scsi0 Channel: 00 Id: 02 Lun: 00
Vendor: PIONEER
Type:

Model: DVD-ROM DVD-303

CD-ROM

Rev: 1.10

ANSI SCSI revision: 02

Host: scsi1 Channel: 00 Id: 00 Lun: 00


Vendor: IBM
Type:

Model: DNES-309170W

Direct-Access

Rev: SA30

ANSI SCSI revision: 03

Thescsi_infotoolusestheinformationin/proc/scsi/scsitoprintouttheSCSI_IDandthemodelofa
specifieddevice.Fromthefileabovescsi_infowouldproducethefollowingoutput:

________________________________________________________________________________________________________

Page17

LinuxITTechnicalTrainingCentre

HardwareConfiguration

________________________________________________
scsi_info /dev/sda
SCSI_ID="0,0,0"
MODEL="IBM DNES-309170W"
FW_REV="SA30"

BootingfromSCSIdisks
ThesystemwillbootfromthedevicewithSCSIID0bydefault.ThiscanbechangedintheSCSIBIOS
whichcanbeconfiguredatboottime.
IfthePChasamixtureofSCSIandIDEdisks,thenthebootordermustbeselectedinthesystemsBIOS
first.

5.Networkcards
Thenetworkinterfacecard(NIC)mustbesupportedbythekernel.Youcangetinformationaboutyour
currentcardusingeitherofthefollowing:
dmesg,lspci,scanpci,/proc/interrupts,/sbin/lsmod.or/etc/modules.conf:

dmesg
Linux Tulip driver cersion 0.9.14 (February 20, 2001)
PCI: Enabled device 00:0f.0 (0004 ->0007)
PCI: Found IRQ 10 for device 00:0f.0
eth0: Lite-On 82cl68 PNIC rev 32 at 0xf800, 00:0A:CC:D3:6E:0F,
IRQ 10
eth0: MII transceiver #1 config 3000 status 7829 advertising

cat/proc/interrupts
0:8729602XTPICtimer
1:4XTPICkeyboard
2:0XTPICcascade
7:0XTPICparport0
8:1XTPICrtc
10:622417XTPICeth0
11:0XTPICusbuhci
14:143040XTPICide0
15:180XTPICide1

/sbin/lsmod
________________________________________________________________________________________________________

Page18

LinuxITTechnicalTrainingCentre

HardwareConfiguration

________________________________________________

ModuleSizeUsedby
tulip
37360
1 (autoclean)

FromtheexamplesaboveweseethattheEthernetcardschipsetisTulip,thei/oaddressis0xf800and
theIRQis10.Thisinformationcanbeusedeitherifthewrongmoduleisbeingusedoriftheresources
(i/oorIRQ)areconflicting.
Thisinformationcaneitherbeusedtoinsertamodulewithadifferenti/oaddress(usingthemodprobeor
insmodutilities)orcanbesavedin/etc/modules.conf(thiswillsavethesettingsforthenextbootup).

6.Settingupmodems
Wefirstneedtodetectthemodem.Ifthemodemisanexternalmodemalloneneedstoconsideristhe
serialportitisusing.HoweverwhendealingwithabuiltinPCImodemweneedinformationabouttheI/O
portandinterruptusedbythedeviceinordertodeterminewhichserialdeviceshouldbeconfigured.
TheModemdevice
Ifwehaveanexternalmodemwecangostraighttothenextsection'Theserialport'.
APCImodemsdevicecanbedetectedwithlspci.(thelistingbelowisfromPCIModemmicroHOWTO):

lspci -v
----- snip ----00:0c.0 Serial controller:US Robotics/3Com 56K FaxModem Model 5610 (rev
01)
(prog-if 02 [16550])
Subsystem: US Robotics/3Com USR 56k Internal FAX Modem (Model 2977)
Flags: medium devsel, IRQ 11
I/O ports at e800 [size=8]
Capabilities: <available only to root>
------ snip ----

NoticethattheI/Oportis0xe800andtheIRQis11
Wecannowusethisinformationandassigntheseresourcestoaserialportdevice.
Theserialport
Themodemusesaserialinterfaceforcommunications.Informationissentthroughthetelephonelineasa
sequenceofbits(serial)overtwowires(inandout).Incomingsequentialdataistranslatedintoparallel
dataforthePCbusandviceversaforbitsofdataleavingthecomputer.Thetranslationisdonebya
UARTchiplocatedontheserialportofthemotherboardorinsideaninternal(PCI)modem.
Toseewhichserialportsweredetectedatboottimeonthesystem,wedothefollowing:
________________________________________________________________________________________________________

Page19

LinuxITTechnicalTrainingCentre

HardwareConfiguration

________________________________________________
dmesg | grep ttyS

/dev/ttyS0, UART: 16550A, Port: 0x03f8, IRQ: 4


/dev/ttyS1, UART: 16550A, Port: 0x02f8, IRQ: 3

Sofar,thesearepreconfiguredserialportswithI/OportsandIRQsgenerallyusedbyahardwareserial
port.
NOTICE
WhenconfiguringanexternalmodemoneonlyhastoconsiderserialdeviceswithIRQ3orIRQ4.The
I/Oportsreportedabovearealsostandardaddressesusedbyhardwareserialports
ThefollowingtableshowstheequivalencebetweenDOSCOMportsandLinuxserialdevices.
SerialportequivalenceDOSLinux
Linux
/dev/ttyS0
/dev/ttyS1
/dev/ttyS2

DOS
COM1
COM2
COM3

Onecanalsousesetserialtoscantheserialdevices.Withthegoptionthisutilitywilltellyouwhich
serialdevicesareinuse:

setserialg/dev/ttyS[01]
/dev/ttyS0,UART:16550A,Port:0x03f8,IRQ:4
/dev/ttyS1,UART:16550A,Port:0x02f8,IRQ:3

NowifwehaveaPCImodemastheonedetectedusinglspcionp.19weneedtoremembertheI/Oport
andIRQsettingused:
HardwaresettingforthePCImodemonp.19
I/Oport

0xe800

IRQ

11

Thistimewewillusesetserialtoassignthesevaluestoaserialdevice(otherthanthehardwareserial
devices)asfollows:

________________________________________________________________________________________________________

Page20

LinuxITTechnicalTrainingCentre

HardwareConfiguration

________________________________________________
setserial/dev/ttyS4port0xe800irq11autoconfig

TheautoconfigoptionautomaticallysetsthecorrectUART.Thiscommandcanbesavedinashell
scriptcalledserial.rcandwillconfiguretheserialporteverytimeweboot.

Asymboliclinkcalled/dev/modempointingtotheusedserialportisoftenusedtoreferencethemodem.
Manuallylinkingthemodemdevice

lns/dev/ttyS1/dev/modem

Thesetserialtoolisalsousedtosetthespeedoftheserialport.
setserialspeedoption Description
spd_hi

use56kbinsteadof38.4kb

spd_vhi

use115kbinsteadof38.4kb

spd_shi

use230kbinsteadof38.4kb

spd_warp

use460kbinsteadof38.4kb

spd_cust

usethecustomdivisortosetthespeedat38.4kb(baudrate=baud_base/
custom_divisor)

spd_normal

use38.4kbwhenabaudrateof38.4kbisselected

Forexamplesettingthespeedfortheserialport/dev/ttyS4to115kbisdoneasfollows:

setserial/dev/ttyS4spd_vhi

DialupConfiguration

Thewvdialcommandlinetoolhasasetupscriptcalledwvdialconfwhichwillscanthesystemfor
modems(allserialandUSBportsarescannedautomatically).Oncethescripthasrunaskeleton
configurationfileisgenerated:

________________________________________________________________________________________________________

Page21

LinuxITTechnicalTrainingCentre

HardwareConfiguration

________________________________________________

Sample/etc/wvdial.conffile:
[DialerDefaults]
Modem=/dev/ttyS1
Baud=115200
Init1=ATZ
Init2=ATQ0V1E1S0=0&C1&D2S11=55+FCLASS=0
;Phone=<TargetPhoneNumber>
;Username=<YourLoginName>
;Password=<YourPassword>

AquickwaytogetstartedistoreplaceDefaultswiththenameofyourprovidersayWorldISP,fillinthe
Usernam/Passwordentriesandtypethefollowing:

wvdialWorldISP

Onecanalsouseminicomtoconfigureaconnection.Thistoolsisfirstconfiguredwiththesswitch:

minicoms
[configuration]
Filenames and paths
File transfer protocols
Serial port setup
Modem and dialing
Screen and keyboard
Save setup as dfl
Save setup as..
Exit
Exit from Minicom

Alltheworkdoneonserialportswillbeusefulinthe'Serial port setup'section,whereasdialling


information(givenbytheISP)canbeenteredbyselectingthemenu'Modem and dialing'
Oncethemodemissetupandiscapableofdiallingtheoutsideworldthenitispossibletoestablisha
serialconnectiontoaremotehost.Togetafullynetworkedconnection(i.eassignanIPaddresstoa
networkinterface)westillneedtostartthepppdwhichwillcreateappp0networkinterfaceandusesthe
pointtopointprotocolPPPtoenableTCP/IPnetworking.Withtoolslikewvdialthisisdoneautomatically
whenneeded.
WinModems
________________________________________________________________________________________________________

Page22

LinuxITTechnicalTrainingCentre

HardwareConfiguration

________________________________________________
Ifalltheaboveconfigurationsfailsthenitlikelythatyouhaveamodemthatmayonlyworkwithsome
addeddrivers.Suchmodemsarecalledwinmodems(seethewinmodemHOWTOforsomecolourful
definitions!).
AwinmodemthatcanbemadetoworkunderLinuxisalsocalledalinmodem.(seethelinmodem
HOWTOformoredetails)

ISDN

ISDNisadigitalversionofthePlainOldTelephoneService(POTS).Itfunctionsinasimilarway,but
insteadofallowingasingledirectanaloguepath,offersanumberof64KBit/Strafficorbearerchannels
andalowbandwidthdatachannel.ISDN2,thebasicserviceofferedinmanycountries,isasocalled
2B+Dserviceasitofferstwobearerchannelsandadatachannel.
ThereareanumberofwaysofusingISDNwithaLinuxmachine.Thesimplestistoemployanexternal
ISDNdevicethatdoesthedialing,authenticationandsessionforyou,presentingtheconnectionoveran
Ethernetnetwork.
IftheLinuxmachineistobedirectlyinterfacedtotheISDNconnection,adevicecalledaTerminal
Adapter(TA)willberequired.ThedetailsofthevariousdifferentinterfacestoTAsareoutsidethescope
ofthiscourse,butfallmainlyintothefollowingcamps.
ModemStyleATcommandInterface
WithserialconnectedTAsandsomeUSBdevices,theLinuxmachineispresentedwithanAT
commandinterfaceexactlyasiftheTAwereamodem.TheTAcanthereforebesetupasifit
wereamodem.Thishastheadvantageofbeingsimpletodo,butislessefficientthansomeother
methodsasittreatsthedatapathasifitwereamodemaswell.Modemsrequirethatsome
charactersareescapedastheyhaveanactiveeffect.ISDNhasnosuchrestrictionandcanpass
anycharacter.
PCI/ISA/PCCARDISDNadaptercardsandisdn4linux
AfarmoreefficientwayofusingyourISDNlineistouseanadaptercardconnecteddirectlytoa
machinebus.Theisdn4linuxprojectseekstoencapsulatealotofthedetailsofmakinga
connectionoverISDNandpresentthefinishedconnectionasjustanothernetworkinterface.The
packageisdn4kutilscontainsallthenecessarysoftware.UnderRedHatrelatedLinux
distributionsthetoolsystemconfignetworkwillsetthisallup.

ADSL

AsynchronousDigitalSubscriberLine(ADSL)haslargelyreplacedISDNandprivateleasedlinesasthe
massmarkethigherbandwidthInternetconnectionmethodofchoice.AswithISDNtheLinuxuserhasa
numberofstrategychoices.Thesimplest,againaswithISDN,istoemployanyofanumberofdifferent
standaloneADSLRouterdevices.ThesepresenttheoutsidelinkviaanEthernetrouter.Nospecial
considerationsneedbetakenontheLinuxmachine.TheADSLrouteristreatedasanordinaryrouter.
ManyoftheseADSLrouterdevicesareactuallythemselvesembeddedLinuxmachines.IftheLinuxuser
requiresacloserconnectiontotheADSLservice,theywillprobablyneedtoacquireequipmentandan
________________________________________________________________________________________________________

Page23

LinuxITTechnicalTrainingCentre

HardwareConfiguration

________________________________________________
ISPaccountcapableofPointtoPointProtocoloverEthernet(PPPoE).ThereareADSLprojectsbased
aroundparticularchipsets,buttheyhavetheirownspecificrequirementsandconfigurationmethods.
PPPoE
ADSLisnotasingleprotocolbutratherabasketofrelatedandinterconnectedprotocolstopped
offwithPointtoPointProtocol(PPP).IftheequipmentandtheISPaccountarecompliant,the
LinuxusercanemployPPPoEtoformtheexternalconnection.TheLinuxmachinewouldinitiatea
PPPoEsessionandaimitattheMACaddressoftheADSLequipment.TheADSLequipment
wouldsetupthelayersbeneaththePPPsessionandpassthePPPframesacrossthoselayers.
Thepackagepppoecontainsallnecessarysoftwareandsetupinformation.

7.PrinterConfiguration
PrintingiscoveredindepthinLPI102.Fromahardwareperspective,theprintersaredetectedatboot
timeautomaticallyandcanbeseeninthedmesgoutput.
Linuxprintinghappensintwostages.Firsttherawdataisfilteredintoapostscriptformat,thentheprinting
itselfishandledbytheghostscript,orgsutility.
Usingprinttool

(notexamined)

Thisutilitycreatesanentryin/etc/printcap.Themainfeatureswhichneedtobespecifiedarethelocation
oftheinput_filter=if,thespool_directory=sdandtheprinter_device=lp.
Iftheprinttoolfailstodetectwhichparallelportcorrespondstotheprinterdeviceyoucanusethedmesg
utilitytorecallthekernel'sinitialparallelportscan.

Hereisanexampleofasystemwithalocalprinterpluggedintothefirstparallelport/dev/lp0
Parallelportscanattheendofdmesg
parport0:PCstyleat0x378(0x778)[SPP,ECP,ECPEPP,ECPPS2]
parport0:detectedirq7;useprocfstoenableinterruptdrivenoperation.
parport_probe:succeeded
parport0:Printer,HEWLETTPACKARDDESKJET610C
lp0:usingparport0(polling)

Sample/etc/printcapfile
#Thisfilecanbeeditedwiththeprinttoolinthecontrolpanel.
##PRINTTOOL3##LOCALcdj550300x300a4{}DeskJet5503{}
lp:\
:sd=/var/spool/lpd/lp:\
:mx#0:\
________________________________________________________________________________________________________

Page24

LinuxITTechnicalTrainingCentre

HardwareConfiguration

________________________________________________
:sh:\
:lp=/dev/lp0:\
:if=/var/spool/lpd/lp/filter:

Figure7:ThegtkbasedprinttoolGUI

Usingcups
Cupsisaneweradministrationandconfigurationtoolforprinters.It'smainconfigurationfilesarestoredin
/etc/cups.Theprintingprocessisthesameexceptthatcupsusesitsownfilterssituatedin
/usr/lib/cups.
TheconfigurationtoolforCUPSisaWebbasedGUIrunningonport631.
Whenusingcupslpdisreplacedbythecupsddaemon.
NOTICE
AlocalprinterisphysicallydetectedatboottimeforbothUSBandparallelconnections.
Informationonthebootprocessisdisplayedatanytimewithdmesg

8.SoundCards
TherearetwosoundsupportprojectsforLinux,namelytheopensoundsystem(OSS)andtheadvanced
Linuxsoundarchitecture(ALSA).InfacttheOSSisacommercialprojectwhichsupportssounddriverson
otherUNIXplatforms.TheoriginalmodifiedOSSdriverswhereintroducedaspartoftheLinux2.0kernel.
TheALSAprojectismorerecentandhasonlybeenintegratedintotheLinux2.6kernel.Forkernelsolder
than2.6,usingALSAdriversoftenmeansrecompilingthekernelexceptforsomeLinuxdistributionssuch
asSusewhichadoptedALSAatanearlystage.
Inmostcasesthecardisconfiguredwhenthesystemisinstalled.Graphicalsoundconfigurationtoolsare
alsoincludedwithallmainLinuxdistributions.
________________________________________________________________________________________________________

Page25

LinuxITTechnicalTrainingCentre

HardwareConfiguration

________________________________________________
Detectingthesoundcard
Asusualwewillusedmesgtoseeifthekernelhasdetectedthesoundcardasfollows:

dmesg|grepiaudio
NeoMagic256AV/256ZXaudiodriver,version1.1p
InitializedNeoMagic256ZXaudioinPCInativemode

NOTICE
Thecommandabovemayreturnnothing,inwhichcaseyoumustsearchtheoutputofdmesgagainand
trytodeterminewhichdevicecorrespondstothesoundcard

Usingthesndconfigtool(LPI101objectivep.167)
Theabovesoundcardwouldbefullyconfiguredifwecouldfindthecorrectkernelmoduleusingthe
informationfoundwithdmesg.IntheOSSframeworkthiskernelmoduleisthenassociatedtoadevice
nameusedbyapplicationscalledsoundslot0(forthefirstsounddevice).
Thisiswhatasoundconfigurationtoolwilldoautomaticallyforus.Wechoose(sinceitisanLPI101
objective)todiscusssndconfig.

ThisisaRedHattoolthatconfiguresaudiodevicesusingtheOSSmodules.Youmayneedtoinstall
sndconfigasitisnolongerinstalledonmostLinuxdistributions.Thenonesimplytypes:

sndconfig

Agraphicalmenuwillbestartedwithamessagesuggestingitwillnowprobeforaudiodevicesonyou
system.Select'OK'.
Onoursystemthefollowinghardwarewasdetected:
NeomagicCorporation|NM2360[MagicMedia256ZXAudio]
Ifnodeviceisdetectedyouwillbepresentedwithalistofmanufacturersandcardmodelssupportedby
OSSfromwhichtochoose.Ifthishappens,youmaywanttochecktheoutputoflspciagainandalsothe
followingsitewithsupportedmodels:http://www.opensound.com/osshw.html
Onceamodelhasbeenchosensndconfigwillattempttoloadtheassociatedkernelmoduleandplaya
sample(surprise!)sound.Ifthisworkedthenthe/etc/modules.conf(coveredinLPI102)isautomatically
modifiedforus.Toillustratehowourparticularcardhasbeenconfiguredhereisthesoundmoduleentry:
________________________________________________________________________________________________________

Page26

LinuxITTechnicalTrainingCentre

HardwareConfiguration

________________________________________________
/etc/modules.conf(entryforsoundcardusedinthissection)
alias sound-slot-0 nm256_audio

________________________________________________________________________________________________________

Page27

LinuxITTechnicalTrainingCentre

HardwareConfiguration

________________________________________________

9.ExercisesandSummary
ReviewQuestions(answersp.165)

YesorNo
1.TherootpartitionofaLinuxsystemmustalwaysbeonanIDEdisk

__________

2.ALinuxsystemcansupportanyUSBdeviceaslongasthekernelhas
beencompiledwithUSBsupport

__________

Glossary

Term

Definition

DMA

DirectMemoryAccessallowscertainhardwarecomponentstoaccessmemoryto
performreadwriteswithouthavingtointerrupttheCPU

I/Oaddress

apredefinedmemoryrangeusedbyhardwaredevicesandtheCPUtoperformread
andwriteoperations

IRQ

signalsenttotheCPUbyadeviceinordertointerruptthecurrentprocessandgetit
todosomethingelse

resourceallocation collectionofDMA,i/oportandIRQsettingsallocatedtoahardwaredevice
SCSI

interfaceusedtotransferdatabetweenadeviceandthecomputerbus.Forexample
thedevicecanbeaharddrive,atapedrive,aCDROM,aCDwriterorascanner

USB

UniversalSerialBusisastandardallowingexternalhardwaredevicestobeattached
toacomputerwithouthavingtoreboot.Thedesignconsistsofahostcontrollerto
whichisattachedaninitialhubdevice.ThishubcanthenaccommodateUSB
devicesormorehubdevicesallowingtoattachupto127devices(includinghubs)to
asinglehostcontroller

Resources

TheWinmodemsandLinuxHOWTO
TheSerialHOWTO
TheModemHOWTO
TheLinuxUSBsubsystem(http://www.linuxusb.org/)
SCSIterminology(http://www.scsita.org/terms/scsiterms.html)
TheLinux2.4SCSIsubsystemHOWTO
TheEthernetHOWTO
________________________________________________________________________________________________________

Page28

LinuxITTechnicalTrainingCentre

HardwareConfiguration

________________________________________________
ThePrintingHOWTO
TheSoundHOWTO
Theisdn4linuxproject(http://www.isdn4linux.de/)
TheRoaringPenguinPPPoEproject(http://www.roaringpenguin.com/penguin/open_source_rp
pppoe.php)

Files
File

Description

/etc/isapnp.conf

aconfigurationfileforisapnpseeisapnp.conf(5)

/proc/dma

listofcurrentlyusedDMAchannels

/proc/interrupts

listofcurrentlyusedinterrupts

/proc/ioports

listofcurrentlyusedi/oports

/proc/pci

listcurrentinformationaboutthePCIbus

/etc/hotplug/usb.usermap listofrecognisedUSBdevices
/var/log/dmesg

logfileforcurrentandboottimekernelmessages

/proc/scsi/scsi

informationaboutallSCSIdevicesseescsi_info(8)

Commands

Command

Description

dmesg

printkernelmessagesinceboottime

hotplug

programusedbythekerneltohandlehardwarerelatedeventsseehotplug(8)

isapnp

toolusedtoinitialiseISAcardspriortokernel2.4seeisapnp(8)

lspci

listallPCIdevicesseelspci(8)

lsusb

listallUSBdevicesseelsusb(8)

pnpdump

pnpdump(8)dumpISAPlugAndPlaydevicesresourceinformation

scsi_info

scsi_info(8)SCSIdevicedescriptiontool

setserial

setserial(8)get/setLinuxserialportinformation

usbmgr

userspacedaemionwhichloadsorunloadsUSBmodules.Itisanalternativetohotplug
andgenerallyusedonDebianbasedsystems

usb.agent

ahotplugagentwhichhandlesUSBrelatedevents

usbmodules

usbmodules(8)listsdrivermodulesthatmaybeabletomanageinterfacesoncurrently
pluggedinUSBdevices.usbmodulesmaybeusedby/sbin/hotplugoroneofits
agents(normally/etc/hotplug/usb.agent)whenUSBdevicesare"hotplugged"intothe
system

wvdial

aPPPdialerseewvdial(1)

________________________________________________________________________________________________________

Page29

LinuxITTechnicalTrainingCentre

HardwareConfiguration

________________________________________________
Exercises
1.

Usethedmesgcommandtoviewthe/var/log/dmesgfile.SearchforkeywordssuchasUSB,tty
orETH0.
WhatarethenamesoftheUSBcontrollersused?
WhataretheIRQsforthefirsttwoserialports?

2.

Investigatethecontentsofthefollowingfiles:
/proc/ioports
/proc/interrupts
/proc/pci
/proc/dma

3.

ThePCIbus:
Investigatetheoutputoflspcivandscanpciv.Whattypeofethernetcardis
present?
Verifythatthereareasmanybusentrieslistedwithlspciand/proc/pci.

4.

USBtools:
Uselsmodandlsusbtodeterminewhichhostcontrollerisusedonyour
system,UHCI,OHCIorEHCI(forUSBv2.0).
Useusbmodulestolistthekernelmodulewhichcanhandlethepluggedininterface.

5.
SCSIdevices

Giventhefollowingcontentsofthefile/proc/scsi/scsideducetheoutputofthe command
scsi_info(seep.17):

Attacheddevices:
Host:scsi0Channel:00Id:00Lun:00

Vendor:PHILIPSModel:CDRW48ARev:P1.3

Type:CDROMANSISCSIrevision:02

________________________________________________________________________________________________________

Page30

LinuxITTechnicalTrainingCentre

ManagingDevices

____________________________________________

ManagingDevices
Prerequisites
ExperiencewiththeLinuxinstallationprocess(alsoseethesectionInstallationonp.1)

Goals
Understandthedifferencebetweenaprimary,anextendedandalogicalpartition
Usepartitioningtoolswhenappropriate(beforeorafteraninstallation)
InstallandcustomisethebootloadersLILOandGRUB
Understandmountpointsandtheroleofthe/etc/fstabfile

Contents
MANAGINGDEVICES.....................................................................................................27
1.DisksandPartitions............................................................................................................. 28
2.PartitioningTools:................................................................................................................ 30
3.Bootloaders......................................................................................................................... 31
4.Manageddevices................................................................................................................ 33
5.Quotas................................................................................................................................. 35
6.ExercisesandSummary...................................................................................................... 36

__________________________________________________________________________________________________

Page31

LinuxITTechnicalTrainingCentre

ManagingDevices

____________________________________________

1.DisksandPartitions

Physicaldisks:
OnarunningLinuxsystem,disksarerepresentedbyentriesinthe/devdirectory.Thekernel
communicateswithdevicesusingauniquemajor/minorpaircombination.Allmajornumbersare
listedin/proc/devices.ForexamplethefirstIDEcontrollersmajornumberis3:
Blockdevices:
1ramdisk
2fd
3ide0
Harddiskdescriptorsin/devbeginwithhd(IDE)orsd(SCSI),aSCSItapewouldbest,andso
on.Sinceasystemcanhavemorethanoneblockdevice,anadditionalletterisaddedtothe
descriptortoindicatewhichdeviceisconsidered.

Table1

Physicalblockdevices

hda

PrimaryMaster

hdb

PrimarySlave

hdc

SecondaryMaster

hdd

SecondarySlave

sda

FirstSCSIdisk

sdb

SecondSCSIdisk

NBInsertinganewSCSIharddrivewithatargetnumberbetweentwoexistingdriveswillbump
upthedeviceletterofthehighernumbereddrive.Thiscancausechaoswithinadisksystem.

DiskPartitions:

Diskscanfurtherbepartitioned.Tokeeptrackofthepartitionsanumberisaddedattheendof
eachphysicaldevice.

Table2

Partitions

hda1

Firstpartitiononfirstharddisk

hda2

Secondpartitiononfirstharddisk

sdc3

ThirdpartitiononthirdSCSIdisk

__________________________________________________________________________________________________

Page32

LinuxITTechnicalTrainingCentre

ManagingDevices

____________________________________________
IDEtypedisksallow4primarypartitions,oneofwhichcanbeextended.Theextended
partitioncanfurtherbedividedintologicalpartitions.Therecanbeamaximumof64partitionsonan
IDEdiskand16onaSCSIdisk.

Example1:Theprimarypartitions(1,2,3,4)and(1,2,5,6,7,8)

Typicaloutputoffdisk

l
DeviceBootStartEndBlocksIdSystem
/dev/hda1*17486297448+bWin95FAT32
/dev/hda27857883213083Linux
/dev/hda37892432132054305Extended
/dev/hda57891235359049683Linux
/dev/hda612361618307641683Linux
/dev/hda716191720819283+83Linux
/dev/hda817211784514048+83Linux
/dev/hda91785183540962683Linux
/dev/hda101836187431323683Linux
/dev/hda11187518837226182Linuxswap

Onthissystemthemainfeaturetonoticeisthatthereare3primarypartitions.Thethirdpartitionis
extended(/dev/hda3)andholds8logicalpartitions.Theprimarypartition/dev/hda3isnotused.In
fact/dev/hda3actsasa'container'andafilesystemexistsonlyontheenclosedlogicalpartitions.
__________________________________________________________________________________________________

Page33

LinuxITTechnicalTrainingCentre

ManagingDevices

____________________________________________
NOTICE
Makesuretodistinguishbetweenprimary,extendedandlogicalpartitions.Alsomakesure
youunderstandthenamingconventionfortheIDEdisksandcontrollers.

2.PartitioningTools:
1.Beforeinstallation:

(notforexampurpose)

PartitionMagic
fips

Noticethatfipsonlyhandlesfat16andfat32.Ontheotherhand,PartitionMagicismuchmore
versatileandcanhandlemostcommonUNIXformatsaswell.
NopartitioningisneededifforexampleC:\andD:\existandtheD:\driveisempty.
Partitioningbeforeinstallation:

2.Duringinstallation:

(notforexampurpose)

__________________________________________________________________________________________________

Page34

LinuxITTechnicalTrainingCentre

ManagingDevices

____________________________________________
WhileinstallingLinuxyouwillhavethechoiceofcreatingnewpartitionsandassociatingeach
partitiontoamountpoint(seep.5).
Foradvancedusersthisisdoneintwosteps:
1.Usethefdisktooltocreatenewpartitions
2.Associateamountpointtoeachpartition

Forintermediateusersmostdistributionsincludeauserfriendlytoolthatdoesboththesestepsat
once:
diskdrake(Mandrake)
DiskDruid(RedHat)

Finally,forbeginnersandbusysysadmins,thelatestLinuxdistributionswillautomaticallyassigna
partitionscheme.

3.OnaRunningSystem:
Oncetheoperatingsystemisinstalledyoucanusethefdiskutilitytoconfigurenewpartitions.
Wewillnextlookatthebasicsyntaxforfdisk

Example:

1)Startpartitioningthefirstharddrive:

fdisk/dev/hda

2)Typemforhelp.Thencreateanewpartitionwithn.
3)Towritethechangestodisktypew.
4)REBOOT.

Thesefourpointsoutlinethestepsyouwouldfollowtocreatenewpartitions.Thelastpoint
isoftenoverlooked.ThisforcesthepartitiontableinthemasterbootrecordMBRtobereread.

__________________________________________________________________________________________________

Page35

LinuxITTechnicalTrainingCentre

ManagingDevices

____________________________________________
NOTICE
Youneedtocreateafilesystemonanewpartitionwithmkfsormke2fsbeforeusingit
Thisendsthesurveyofavailablepartitioningtools.Wenexttakealookatbootloaders.

3.Bootloaders
TheMBRoccupiesthefirstsectorofthedisk(512bytes)andcontainsthepartitiontablestogether
withabootloader.Atboottimethebootloaderreadsthepartitiontableslookingforapartition
markedactiveandloadsthefirstsectorofthispartion.

LILOtheLinuxBootloader
Thereareroughly3partsinvolved:
1.LILO
Thisistheloaderitself.LILOisinstalledontheMBRandloadsthesecondstagebootloader,
generallysituatedin/boot/boot.b.

2./etc/lilo.conf
Themainoptionsarespecifiedhere

boot*
whereLILOshouldbeinstalled(/dev/hdaistheMBR)
install
whichsecondstagetoinstall(boot.bisthedefault)
prompt
givetheuserachancetochooseanOStoboot
default
nameoftheimagethatwillbebootedbydefault
timeout
usedwithprompt,causesLILOtopause(unitsare1/10ofasec)
image*
pathtothekerneltoboot(onecanuseothertochainload)
label*
nameoftheimage.Thisisthenameausercantypeatthebootprompt
root*
thenameofthediskdevicewhichcontainstherootfilesystem/
readonly*
mounttherootfilesystemreadonlyforfscktoworkproperly
append
givekernelparametersformodulesthatarestaticallycompiled.
linear/lba32 theseoptionsaremutuallyexclusive.BothaskLILOtoreadthediskusing
LinearBlockAddressing.linearistypicallyusedforverylargedisks.lba32isusedtoallow
boottimeaccesstodatabeyondthefirst1024cylinders(alsoseep.41)

3./sbin/lilo
Thisbinaryreadsitsconfigurationfile/etc/lilo.confandinstallstheLILObootloader.
/sbin/liloshouldberuneverytimeachangeismadeto/etc/lilo.conf
__________________________________________________________________________________________________

Page36

LinuxITTechnicalTrainingCentre

ManagingDevices

____________________________________________

GRUBtheGrandUnifiedBootloader

GRUBisalsoinstalledontheMBR.YoucaneitheralterthisMBRwiththe/sbin/grubshellorusea
configurationfilecalled/boot/grub/grub.confwhichwillbereadby/sbin/grubinstall
DetailedinformationaboutGRUBcanbefoundintheinfopages

Mainsectionsin/boot/grub/grub.conf:
1.General/Global
default
timeout

imagethatwillbootbydefault(thefirstentryis0)
prompttimeoutinseconds

2.Image
title
root
kernel
ro
root
initrd

nameoftheimage
wherethe2ndstagebootloaderandkernelaree.g(hd0,0)is/dev/hda
pathforthekernelstartingfromthepreviousroote.g/vmlinuz
readonly
thefilesystemroot
pathtotheinitialrootdisk

Example

grub.conf

default=0
timeout=10
splashimage=(hd0,0)/grub/splash.xpm.gz
titleLinux(2.4.1814)
root(hd0,0)
kernel/vmlinuz2.4.1814roroot=/dev/hda5
initrd/initrd2.4.1814.img

4.Manageddevices
Atboottimethe/etc/fstabfileassignsmountpointsforblockdevices.
__________________________________________________________________________________________________

Page37

LinuxITTechnicalTrainingCentre

ManagingDevices

____________________________________________
The/etc/fstabformat

devicemountpointfstypeoptionsdumpnumberfscknumber

Sample/etc/fstab
LABEL=/
/
ext2 defaults
11
LABEL=/boot/boot ext2 defaults
12
LABEL=/home
/home ext3 defaults
12
/dev/fd0
/mnt/floppyauto noauto,owner
00
LABEL=/usr
/usr
ext2 defaults
12
LABEL=/var
/var
ext3 defaults
12
none
/proc
proc defaults
00
none
/dev/shm
tmpfs defaults
00
none
/dev/pts
devptsgid=5,mode=620 00
/dev/hdc9
swap,pri=1 swap defaults
00
/dev/cdrom/mnt/cdromiso9660noauto,owner,kudzu,ro00

Themountcommandisusedtomakeaparticulardeviceavailableonaspecificdirectory(mount
point).Thesyntaxis:

mountt[FSTYPE]o[OPTIONS]DEVICEDIRECTORY
ForexamplewecanmountaCDROMonthemountpoint/mnt/cdromwith:

mounttiso9660/dev/cdrom/mnt/cdrom

Onarunningsystemthe/etc/fstabfilealsoactsasashortcutforassigningaresourcetoaspecific
directory.Forexample:

mount/dev/cdrom

Themountutilityreadsfstabanddeduceswheretomounttheresource.Noticethatsomeofthe
devicesareaccessedusingalabel.Labelsareassignedtodeviceswiththetune2fstool:

__________________________________________________________________________________________________

Page38

LinuxITTechnicalTrainingCentre

ManagingDevices

____________________________________________
tune2fsL/usr/local/dev/hdb12

Optionsummaryformount:
readwriteandreadonly
rw,ro
thedeviceisnotmountedatboottime
noauto
thedevicecanbereadandunmountedbyallusers
users
thedevicecanbeunmountedonlybytheuser
user
thedevicewillchangeit'spermissionandbelongtotheuserthatmountedit
owner
usrquota startuserquotasonthedevice
grpquota startgroupquotasonthedevice

NOTICE
Rememberthatmountawillmountallfilesytemsin/etc/fstabthathavenotbeen
mountedanddonothavetheoptionnoauto

Theumountcommandwillunmountadevice.Noticethatthecommandismisspelled!Thesyntax
is:

umountDEVICEorMOUNTPOINT

ForexamplethefollowingcommandswillbothunmounttheCDROMdevice:

umount/dev/cdrom
or

umount/mnt/cdrom

5.Quotas
Thequotatoolsallowadministratorstosetupquotaswithouthavingtoreboot.Herearethesteps.
1.Edit/etc/fstabandaddusrquotatotheoptions
__________________________________________________________________________________________________

Page39

LinuxITTechnicalTrainingCentre

ManagingDevices

____________________________________________
2.Remountthepartition:

mountoremount<device>

3.Startthequotastats:

quotacheckca

Thepreliminaryaquota.userdatabasefileisgeneratedatthetopofthedirectory.

4.Editquotasforeachuser:

edquotau<user>
Hereasoft/hardlimitmustbesetforboththenumberofblocksandinodesavailableforeachuser.
Thesystemwillallowtheusertoexceedthesoftlimitduringacertaingraceperiod.After
thegraceperiodhasexpiredthesoftlimitwillbeenforcedasahardlimit.
5.STARTenforcingquotas:

quotaona

Userscanquerythequotastatuswithquota.Thesystemadministratorcangeneratereportswith
repquotaorquotastats.

__________________________________________________________________________________________________

Page40

LinuxITTechnicalTrainingCentre

ManagingDevices

____________________________________________

6.ExercisesandSummary
ReviewQuestions(answersp.165)
YesorNo
1.WhenLILOisinstalledandfurtherchangesaremadetolilo.confitis
notnecessarytorerun/sbin/lilo

______

2.WhenGRUBisinstalledandfurtherchangesaremadetogrub.confitis
notnecessarytorerungrubinstall

______

3.If/rootisbeyondthe1024cylinderlimitthenaLinuxsystemmaynotboot

______

4.Quotasmayonlybeusedonanentirepartition

______

Glossary

Term

Description

partition

anindependentsectionofaharddrivewhichcaneitherbeusedtodirectly
storedataorcanbefurtherdividedinto(logical)partitions.Sinceallpartitions
mountedandmanipulatedbytheoperatingsystemhaveaseparate
filesystemandareconsideredasindependentdevices,apartitionisalso
sometimecalleda'device'orevena'filesystem'

primary(partition)

partitiondescribedbyoneoftheoriginalpartitionrecordkeptinthepartition
table.Onlyfoursuchrecordsareavailable,thereforediskscanonlyhavefour
primarypartitions

extended(partition) aprimarypartitionwhosepartitionrecordcontainsalinkedlistofpartition
recordsmakingitpossibletocreatefurtherpartitionscalled'logicalpartitions'
asopposedtoprimary
logical(partition)

apartitioncontainedinanextendedpartition

MBR

thefirstsector(512bytes)ofaharddrivewhichcontainsthebootloaderand
thediskspartitiontables

1024cylinderlimit

whenusingCHSaddressingoldBIOSsystemswoulduse10bitstoreadthe
numberofcylinders,8bitsfortheheadsand6bitsforthesectors.Thiswould
allowaccesstodiskswithamaximumsizeof(2^10)*(2^8)*(2^61)*512bytes
whichcorrespondsto8.5GB(metric).Whenrunning/sbin/liloaddressesare
giveninCHSform(unlesslba32orlinearisused)fortheBIOStoread.Ifthe
secondstagebootloader/boot/boot.bis'further'than1024cylindersaway
fromtheMBRthenthesystemwillnotboot

bootloader

codestoredinthefirst512bytesofadiskwhichisreadbytheBIOSand
usedtostartanoperatingsystem

__________________________________________________________________________________________________

Page41

LinuxITTechnicalTrainingCentre

ManagingDevices

____________________________________________
GRUB

GrandUnifiedBootloader

LILO

LinuxbootLoader

quotas

mechanismavailableperdevicetosetrestrictionsontheamountofinodes
anddatablocksperuserorgroup

grace

timelimitforfilesanddatathathaveexceededtheirsoftlimit

Files
File

Description

/boot/boot.b

TheLILOsecondstagebootloader

grub.conf

configurationfileforGRUB

/etc/fstab

fstab(5)Thefilefstabcontainsdescriptiveinformationaboutthevariousfile
systems.fstabisonlyreadbyprograms,andnotwritten;itisthedutyofthe
systemadministratortoproperlycreateandmaintainthisfile

/etc/lilo.conf

configurationfilereadbythebootloaderinstallationmapper/sbin/lilo

/proc/devices devicesfoundonthesystemandtheirassociatedmajornumber
aquota.user

databasefilestoredontherootofthedevicewhereuserquotasareinforced

Commands
Command

Descriptionorapropos

/sbin/lilo

lilo(8)installbootloader

edquota

edquota(8)edituserquotas

fdisk

fdisk(8)partitiontablemanipulatorforLinux

grubinstall

grubinstall(8)installGRUBonyourdrive

mount

mount(8)mountafilesystem

quotas

quota(1)displaydiskusageandlimits

quotacheck

quotacheck(8)scanafilesystemfordiskusage,create,checkandrepairquota
(database)files

quotaon

quotaon(8)/quotaoffturnfilesystemquotasonandoff

quotastats

quotastats(8)programtoqueryquotastatistics

repquota

repquota(8)summarizequotasforafilesystem

tune2fs

tune2fs(8)adjusttunablefilesystemparametersonsecondextendedfilesystems

usrquota,grp (notacommand)optionsetin/etc/fstabtoenablequotasonadevice
quota
umount

umount(8)unmountfilesystems

__________________________________________________________________________________________________

Page42

LinuxITTechnicalTrainingCentre

ManagingDevices

____________________________________________
Exercises
1.

Create1newpartitiononthe/dev/hdadeviceusingfdisk.
fdisk /dev/hda
HINT: Tocreateanewpartitiontypen.Thepartitiontypedefaultsto83(Linux)
Towritethenewpartitiontabletypew.
Thepartitiontableneedstoberead:REBOOTthecomputer!

2.

Makeanewfilesystem(format)ononeofthepartitions:
mkfs<device>

3.

(i)Makeadirectorycalleddataintherootdirectory.
mkdir /data

(ii)Edit/etc/fstabandallocatethemountpoint/datatothisnewresource
<device>

4.

/data ext2

defaults

0 2

Forcemounttoread/etc/fstab:
mounta
Ifthisdoesn'tworkcheckthateachentryiscorrectinthefstabandmakesurethatthe
directory/dataexists(2(i))

5.

Followthestepsinthischaptertoenforcequotasonthisdevice.
Afterstep(2)runthemountcommandandlookattheoutput.Whichoptionfrom
/etc/fstabcanbeseenshowingthatquotasareavailabeonthedevice?_________
Afterstep(3)whichfileiscreatedinthe/datadirectory?__________
Beforetestingquotasforwithnonrootusers,addreadwritepermissionson/data
chmod o+rw /data
Inextremecasesitmaybeeasiertorebootandlettheinitscriptsbuildtheaquota.user
(oraquota.group)file.Ifnothingisshowingwiththequotas,repquota,orquotastats
toolsmakesureyouhavereadwriteaccessforeveryoneon/data[chmoda+rw/data]

6.

(OPTIONAL)TheinstructorcomputerhasaNFSshare.Findoutwhichdirectoryis
sharedandedit/etc/fstabtomountthisshareon/mnt/nfs.Usethenoautooptionfotthe
sharenottomountatboottime.

7.SWAPPINGbootloaders
__________________________________________________________________________________________________

Page43

LinuxITTechnicalTrainingCentre

ManagingDevices

____________________________________________
a.UninstallLILOfromtheMBR(orthefloppy)
lilo u
b.Modifythegrub.confsampleonp.28toreflectyoursystem
c.InstallGRUBonthefloppywithgrubinstall/dev/fd0

__________________________________________________________________________________________________

Page44

LinuxITTechnicalTrainingCentre

TheLinuxFilesystem

_________________________________________________

TheLinuxFilesystem
Prerequisites
ExperiencewiththeLinuxinstallationprocess(alsoseethesectionInstallationonp.1)

Goals
IntroducethebasedirectoriesandconceptsfromtheFileSystemHierarchy(FHS)
Makeafilesystemofanytype(e.gEXT2orEXT3)onapartition
Monitorfreespaceperdeviceordirectory
UnderstandtheUNIXlikefileanddirectorypermissions

Contents
THELINUXFILESYSTEM............................................................................................................. 39
1.TheFilesystemStructure.................................................................................................................... 40
2.FormattingandFileSystemConsistency...........................................................................................42
3.MonitoringDiskUsage....................................................................................................................... 45
4.FilePermissionsandAttributes.......................................................................................................... 46
5.ExercisesandSummary..................................................................................................................... 52

____________________________________________________________________________________________________________

Page45

LinuxITTechnicalTrainingCentre

TheLinuxFilesystem

_________________________________________________

1.TheFilesystemStructure
Afilesystemissimilartoatreestructure.Therootofthetreeisrepresentedatthetopandtheleavesbelow.
Asmentionedearlier,oncepartitionshavebeencreatedeachpartitionmustbegivenamountpoint.Thisis
typicallydoneatinstallationtime.Tohelpusunderstandwherethingsarekept,letuslookattheLinuxfile
systemhierarchy.
ThetopofaLinuxfilesystemhierarchystartsatroot(/).ThisissimilartoC:\underDOSexceptthatC:\is
alsothefirstdevice,whereastherootdirectorycanbemountedanywhere.

Figure1:Thebasedirectories

Thebasedirectoriesarethefirstsubdirectoriesundertherootdirectory.Theseareinstalledbyanrpm
packageusuallycalledfilesystem.

rpm -ql filesystem

Duringthebootingprocessthekernelfirstmountstheroot(/)partition.Inordertomountandcheckany
furtherpartitionsandfilesystemsacertainnumberofprogramssuchasfsck,insmodormountmustbe
available.
____________________________________________________________________________________________________________

Page46

LinuxITTechnicalTrainingCentre

TheLinuxFilesystem

_________________________________________________

Thedirectories/dev,/bin,/sbin,/etcand/libmustbesubdirectoriesofroot(/)andnotmountedon
separatepartitions.Addedtothis,theremustbeanemptydirectory/procontherootdeviceusedbythe
kerneltoreportinformationabouttheoperatingsystem(e.gprocesses,memorystatistics,etc...)

Basedirectories:

/binand/sbin
Containbinariesneededtobootupthesystemandessentialcommands.

/dev
Locationfordeviceorspecialfiles

/etc
Hostspecificconfigurationfiles

/lib
Sharedlibrariesforbinariesin/binand/sbin.Alsocontainskernelmodules

/mnt/or/media(Suse)
Mountpointforexternalfilesystems

/proc
Kernelinformation.Readonlyexceptfor/proc/sys/

/boot
ContainstheLinuxkernel,thesystemmapsandthesecondstagebootloaders.

/home(optional)
Thedirectoriesforusers.Initiallycontainsthecontentsfrom/etc/skel/

/root(optional)
Thedirectoryforuserroot

/tmp
Temporaryfiles

/usr
UserSpecificResource.Mainlystaticandshareablecontent

____________________________________________________________________________________________________________

Page47

LinuxITTechnicalTrainingCentre

TheLinuxFilesystem

_________________________________________________

/usr/localor/opt(optional)
Addonsoftwareapplications.Canalsocontainsharedlibrariesforaddonsoftware.

/var/www,/var/ftp/or/srv(Suse)
LocationforHTMLpagesandanonymousFTPdirectories.

/var
Variabledata,suchasspoolsandlogs.Containsbothshareable(eg./var/spool/mail)andnon
shareable(eg./var/log/)subdirectories.

2.FormattingandFileSystemConsistency
Inordertoorganisedataonadiskpartitiononeneedstocreateafilesystem.Atinstallationtimeyouwillbe
askedwhichtypeoffilesystemmustbeused.
Manyfilesystemtypesaresupported.Theext2filesystemtypeisthedefaultandisalsoknownasLinux
Native.Insomemorerecentinstallers,ext3isthedefault.Thisisreallyonlyanext2filesystemwithajournal
patchedontop.
AdifferentfilesystemtypemustbeusedforSWAP.ThefilesystemforSwapisoftypeswapandcannotbe
anythingelse.

TheSecondExtendedFileSystem
Letstakeacloserlookattheext2(secondextended)filesystem.Theext2consistsofblocksofsize1024
bytes=1KB(default).Withoutenteringintotoomuchdetail,therearethreetypesofblocks:
Superblocks:

Repeatedevery8193blocks.Containsinformationaboutblocksize,freeinodes,lastmountedtime,etc
Inodes:

Containspointerstodatablocks.Thefirst12blocksofdataaredirectlyaccessed.Ifthedataexceeds12KB,
thenindirectinodesactasrelays.
Eachinodeis256bytesandcontainstheuser,group,permissionsandtimestampoftheassociateddata.
DataBlocks:
Theseareeitherfilesordirectoriesandcontaintheactualdata.
____________________________________________________________________________________________________________

Page48

LinuxITTechnicalTrainingCentre

TheLinuxFilesystem

_________________________________________________
Formattingtools
Thefilesystemssupportedbythekernelallowonetoreadfromapreformatteddisk.Tocreatethesefile
systemswhilerunningaLinuxsystemonealsoneedstoinstalltheassociatedformattingtools.
Theformattingtoolforext2ismkfs.ext2ormke2fs.Similarlytheformattingtoolforthexfsfilesystemtype
fromSiliconGraphicswillbemkfs.xfsandmayhavetobeinstalledseparately.
Themkfstoolactsasafrontforallthesefilesystemtypes.Thesyntaxis:
mkfst<fstype><DEVICE>

Noticethattheext3isanext2filesystemtypeonwhichajournalingsystemhasbeenadded(seethe
exercisesfordetails).

Example1:Makingajfsfilesystem

mkfstjfs/dev/hda12

Example2:Makingaext2filesystem

mke2fs/dev/hda11[ormkfstext2/dev/hda11]

FileSystemConsistency
Ifthefilesystemisdamagedorcorrupt,thenthefsckutilityshouldberunagainstthepartition(theminimum
requirementisthatthefilesystembeunmountedormountedreadonly).
fsckactsasafrontthatautomaticallydetectsthefilesystemtypeofapartition.Thenaswithmkfs,thetools
fsck.ext2,fsck.ext3willbecalledaccordingly.SinceEXT2isthemainfilesystemtypeforLinuxthereisa
e2fsckcommandthatonlyhandlesthisfilesystemtype.

Youcanexplicitlyspecifyafilesystemtypewiththefollowingsyntax:
fsckt<fstype><device>

____________________________________________________________________________________________________________

Page49

LinuxITTechnicalTrainingCentre

TheLinuxFilesystem

_________________________________________________
Example:Checkingareiserfsfilesystemonthe/dev/sdb10device:

fscktreiserfs/dev/sdb10
fsck.reiserfs/dev/sdb10

FileSystemDebugCommands
Thedebugfsanddumpe2fsareseldomusedbutcanbeusefulinprovidinglowlevelinformationaboutan
ext2orext3filesystem.
debugfs[bblocksize][ssuperblock][fcmd_file][Rrequest][V][[w][c][i][device]]
Thedebugfsprogramisaninteractivefilesystemdebugger.Itcanbeusedtoexamineandchangethe
stateofanext2/3filesystem.
Onceinthedebugfsshell,internalcommandscanthenbeusedtochangedirectory,examineinodedata,
removefiles,createlinks,dumptheext3journallogsetc.Whilethisisaverypowerfulcommand,itshould
beusedwithcaution,generallyonlyafterthefsckcommandhasfailedtomakeanyheadway.

dumpe2fs[bfhixV][obsuperblock][oBblocksize]device
dumpe2fsprintsthesuperblockandblockgroupinformationforthefilesystempresentondevice.
dumpe2fs /dev/hda1
dumpe2fs 1.35 (28-Feb-2004)
Filesystem volume name:
/boot1
Last mounted on:
<not available>
Filesystem UUID:
d741042c-3eaf-49ee-94c1-7dd8c5459764
Filesystem magic number: 0xEF53
Filesystem revision #:
1 (dynamic)
Filesystem features:
has_journal ext_attr resize_inode dir_index
filetype needs_recovery sparse_super
Default mount options:
(none)
Filesystem state:
clean
Errors behavior:
Continue
Filesystem OS type:
Linux
Inode count:
25584
Block count:
102280
Reserved block count:
5114
Free blocks:
80564
Free inodes:
25537
First block:
1
Block size:
1024
Fragment size:
1024
Reserved GDT blocks:
256
Blocks per group:
8192
Fragments per group:
8192
Inodes per group:
1968
____________________________________________________________________________________________________________

Page50

LinuxITTechnicalTrainingCentre

TheLinuxFilesystem

_________________________________________________
Inode blocks per group:
Filesystem created:
Last mount time:
Last write time:
Mount count:
Maximum mount count:
Last checked:
Check interval:
Reserved blocks uid:
Reserved blocks gid:
First inode:
Inode size:
Journal inode:
Default directory hash:
Directory Hash Seed:
Journal backup:

246
Sat May 7 10:40:51 2005
Sun May 29 04:08:01 2005
Sun May 29 04:08:01 2005
10
-1
Sat May 7 10:40:51 2005
0 (<none>)
0 (user root)
0 (group root)
11
128
8
tea
50108791-6a0a-41ff-9608-0485c993eaf9
inode blocks

Group 0: (Blocks 1-8192)


Primary superblock at 1, Group descriptors at 2-2
Block bitmap at 259 (+258), Inode bitmap at 260 (+259)
Inode table at 261-506 (+260)
0 free blocks, 1942 free inodes, 2 directories
Free blocks:
Free inodes: 27-1968
[....]

3.MonitoringDiskUsage
Usingmount

anddf:
Boththesetoolsworkonadevicelevel,asopposedtoadirectorylevel.Themountandumounttools
maintainthelistofmountedfilesystemsin/etc/mtab.
Typingmountwithnooptionswillshowallfilesystemscurrentlymounted.Theoutputissimilarto/etc/mtab.
Noticethatthekernelalsokeepstrackofmountedfilesystemsin/proc/mounts.
InadditiontoshowingallmounteddevicesthedftoolwillalsoshowUsedandAvailablediskspace.By
defaultthisisgiveninblocksof1K.

df -h

Filesystem

Size

Used Avail Use% Mounted on

____________________________________________________________________________________________________________

Page51

LinuxITTechnicalTrainingCentre

TheLinuxFilesystem

_________________________________________________
/dev/hda9

289M

254M

20M

93% /

/dev/hda2

23M

7.5M

14M

35% /boot

none

62M

61M

/dev/hda5

1.4G

181M

1.1G

13% /share

/dev/hda7

787M

79M

669M

11% /tmp

/dev/hda3

4.3G

3.4G

813M

81% /usr

/dev/hda6

787M

121M

627M

17% /var

//192.168.123.2/share

12G

8.8G

3.7G

0% /dev/shm

71% /mnt/smb

Usingdu
:
Thistoolwilldisplaydiskusage.Thisisdoneonaperdirectorybasis.Noticethatducannotdisplayavailable
spacesincethisinformationisonlyavailableatadevicelevel.
Thefollowingcommandwilllistthecurrentusageofthe/etcdirectoryinhumanreadableunits(usingtheh
switch)andwillonlyprintthegrandtotal(usingthesswitch):
du -sh /etc

62M

/etc/

4.FilePermissionsandAttributes

____________________________________________________________________________________________________________

Page52

LinuxITTechnicalTrainingCentre

TheLinuxFilesystem

_________________________________________________

Changingpermissionsandowners
Fromthepreviousfigureweseethatpermissionscanbeacteduponwithchmod.Thereare3categoriesof
ownershipforeachfileanddirectory:
u:avaliduserwithanentryin/etc/passwd
g:avalidgroupwithanentryin/etc/group
o:other

Example:
rwrwr1jadesales24880Oct2517:28libcgic.a
ChangingPermissionswithchmod:

chmodg=r,orlibcgic.a
chmodg+wlibcgic.a

Changinguserandgroupwithchownandchgrp:

chownrootlibcgic.a
chgrpapachelibcgic.a

____________________________________________________________________________________________________________

Page53

LinuxITTechnicalTrainingCentre

TheLinuxFilesystem

_________________________________________________
NOTICE
Ausefuloptionforchmod,chownandchgrpisRwhichrecursivelychanges
ownershipandpermissionsthroughallfilesanddirectoriesindicated.

Symbolicandoctalnotation
Permissionscanberead=r,write=wandexecute=x.Theoctalvaluesofthesepermissionsarelistedinthe
nexttable.

Octalandsymbolicpermissions.
Symolic
read
write
execute

octal
4
2
1

binary
'100'
'010'
'001'

Permissionsapplytotheuser,thegroupandtoothers.Anitemhasasetof3groupedpermissionsforeach
ofthesecategories.

Howtoreada755orrwxrxrxpermission
user
rwx
4+2+1=7

group
r_x
4+1=5

other
r_x
4+1=5

Thestandardpermission
UNIXsystemcreatefilesanddirectorieswithstandardpermissionsasfollows:
Standardpermissionfor:
Files
Directories

666
777

rwrwrw
rwxrwxrwx

Umask
Everyuserhasadefinedumaskthataltersthestandardpermissions.Theumaskhasanoctalvalueandis
subtracted(*)fromtheoctalstandardpermissionstogivethefilespermission(thispermissiondoesn'thavea
nameandcouldbecalledthefile'seffectivepermission).
(*)Whilesubtractionworksinmostcases,itshouldbenotedthattechnicallythestandardpermissionsand
theumaskarecombinedasfollows:
____________________________________________________________________________________________________________

Page54

LinuxITTechnicalTrainingCentre

TheLinuxFilesystem

_________________________________________________
FinalPermissions=StandardPermissions(logicalAND)(NOT)Umask
Onsystemswhereusersbelongtoseparategroups,theumaskcanhaveavalueof002.
Forsystemswhichplaceallusersintheusersgroup,theumaskislikelytobe022.

SUIDpermissions
Anexecutablecanbeassignedaspecialpermissionwhichwillalwaysmakeitrunastheownerofthisfile.
ThispermissioniscalledSUIDmeaning'setuserID'.Ithasasymbolicvaluesoranumericalvalue4000.
AdministrativetoolsmayhavetheSUIDbitsetinordertoallownonrootuserstochangesystemfiles.
Forexamplethepasswdcommandcanberunbyanyuserandwillinteractivelychangehisorhercurrent
password.Thispasswordwillbesavedto/etc/passwdor/etc/shadow.Howeverboththesefilesbelongto
userrootwithtypicalpermissionsof644and600respectively.
ThisproblemhasbeensolvedbysettingtheSUIDbitonpasswdhenceforcingittorunasuserrootwiththe
correctpermissionstomodify/etc/passwdor/etc/shadow.
TheSUIDonpasswd

ls -l $(which passwd)
-r-s--x--x

1 root

root

18992 Jun

2003 /usr/bin/passwd

NOTICE
TheSUIDbitisshowninsymbolicforminthecommandabove.Itispossibletogetmoreinformationabout
afileusingstataswellasseeingtheoctalrepresentationofthepermissionsasfollows:

stat /usr/bin/passwd
File: `/usr/bin/passwd'
Size: 18992

Blocks: 40

Device: 305h/773d

IO Block: 4096

Inode: 356680

Access: (4511/-r-s--x--x)

regular file

Links: 1

Uid: ( 0/ root)

Gid: ( 0/ root)

WARNING!WARNING!WARNING!
TheSUIDpermissionisoftenassociatedwithsecurityissues.Hereisanexamplethatillustratesthis.
1.Auserwouldliketoreaduserroot'smail.Forthishechangestheenvironmentalvariableasfollows:
export MAIL=/var/spool/mail/root
____________________________________________________________________________________________________________

Page55

LinuxITTechnicalTrainingCentre

TheLinuxFilesystem

_________________________________________________
2.Theuserthenusesthecommandmail,hopingtoseesomething!
mail
/var/spool/mail/root: Permission denied
Sofaritdoesn'twork.Thiswouldbetooeasy!
ButifrootcanbeconvincedtosettheSUIDbitonmailthepreviouscommandswouldallowanyuserto
readanybody'smail(includingroot).

Thenextexamplesaredangerous.Why?

chmod4755/bin/cat
chmodu+s/bin/grep

SGIDpermissions
TheSGIDisapermissionsimilartoSUIDthatissetforgroupmembers.Thesymbolicvalueissandthe
octalvalueof2000.
SettingSGIDonadirectorychangesthegroupownershipusedforfilessubsequentlycreatedinthatdirectory
tothedirectoriesgroupownership.Noneedtousenewgrptochangetheeffectivegroupoftheprocess
priortofilecreation(seeexercisep.63).
Examples:

chmod2755/home/data
chmodg+s/bin/wc

Thestickybit
Thestickybitpermissionwithvalue1000hasthefollowingeffect:

Appliedtoadirectoryitpreventsusersfromdeletingfilesunlesstheyaretheowner(idealfor
directoriessharedbyagroup)
Appliedtoafilethisusedtocausethefileorexecutabletobeloadedintomemoryandcausedlater
accessorexecutiontobefaster.Thesymbolicvalueforanexecutablefileistwhileforanon
executablefilethisisT.Asfilesystemcachingismoregenericandfaster,filestickybitstendnotbe
supportedanymore.

Examples:
____________________________________________________________________________________________________________

Page56

LinuxITTechnicalTrainingCentre

TheLinuxFilesystem

_________________________________________________
chmod1666/data/store.txt
chmodo+t/bin/bash

FileAttributes

Alongsidethestandardpermissionsthereisanothersystemthatcanbeusedtochangethewayafilecanbe
used.FileAttributesdonotshowupinthe'ls'command.The'lsattr'commandmustbeusedinstead.The
'chattr'commandisusedtosetanddroptheseattributes.

Thefollowingattributesareavailable.Pleasenotethecase.
'A'WhenafilewiththeAattributesetisaccessed,itsatime(accesstime)recordisnotmodified.Thisavoids
acertainamountofdiskI/O,typicallyfortemporaryfiles.Dobeawarethatsometools,suchastmpwatch,
relyontheatimerecordtodetermineifthefilehasbeenusedrecently.Iftheatimerecordisnotbeing
updatedthefile'sstatusmightbemisinterpreted.

'a'Afilewiththeaattributesetcanonlybeopeninappendmodeforwriting.Onlythesuperuserora
processpossessingtheCAP_LINUX_IMMUTABLEcapabilitycansetorclearthisattribute.Thisisprobably
mosteffectivelyusedonsystemlogfiles,topreventintrudersremovingevidenceoftheirpassage.Dobe
awarethatinorderfortheintrudertohaveanychanceofeditingtheselogfiles,theyneedtohaveroot
access.Withrootaccesstheycouldremovethe'a'attribute,maketheeditsandthenreestablishthe'a'
attribute.

'c'Afilewiththecattributesetisautomaticallycompressedonthediskbythekernel.Areadfromthisfile
returnsuncompresseddata.Awritetothisfilecompressesdatabeforestoringthemonthedisk.NBSadly,
whiletheattributeissetonthefileandisdisplayedbythelsattrcommand,itisnotyethonouredbytheext2
orext3filesystemkerneldrivers.

'D'WhenadirectorywiththeDattributesetismodified,thechangesarewrittensynchronouslyonthedisk;
thisisequivalenttothedirsyncmountoptionappliedtoasubsetofthefiles.Whenthisattributeisin
operationagainstadirectory,thefollowingoperationsaresynchronouswithinthatdirectory:create,link,
unlink,symlink,mkdir,rmdir,mknodandrename.

'd'Afilewiththedattributesetisnotcandidateforbackupwhenthedump(8)programisrun.

____________________________________________________________________________________________________________

Page57

LinuxITTechnicalTrainingCentre

TheLinuxFilesystem

_________________________________________________
'i'Afilewiththei(immutable)attributecannotbemodified:itcannotbedeletedorrenamed,nolinkcanbe
createdtothisfileandnodatacanbewrittentothefile.Onlythesuperuseroraprocesspossessingthe
CAP_LINUX_IMMUTABLEcapabilitycansetorclearthisattribute.

'j'Afilewiththejattributehasallofitsdatawrittentotheext3journalbeforebeingwrittentothefileitself,if
thefilesystemismountedwiththe"data=ordered"or"data=writeback"options.Whenthefilesystemis
mountedwiththe"data=journal"optionallfiledataisalreadyjournalledandthisattributehasnoeffect.Only
thesuperuseroraprocesspossessingtheCAP_SYS_RESOURCEcapabilitycansetorclearthisattribute.

's'Whenafilewiththesattributesetisdeleted,itsblocksarezeroedandwrittenbacktothedisk.NBAs
withthe'c'attribute,thisattributeishonouredbyeverythingexceptthekernelfilesystemdriver.

'S'WhenafilewiththeSattributesetismodified,thechangesarewrittensynchronouslyonthedisk;thisis
equivalenttothesyncmountoptionappliedtoasubsetofthefiles.Itismostoftenusedforthe'cookedfiles'
usedbydatabaseprogramstoholdtheirdata.Whenusedinthiswaytheadditionoftwodifferentcaching
systemstogetherisavoided.Thecachingsystemofthedatabase,whichisoptimisedforthatsystemsuseof
data,isallowedtowritedirecttodisk.

'T'The'T'attributeisonlyusablewhenusingthe2.6.xkernel.The'T'attributeisdesignedtoindicatethetop
ofdirectoryhierarchies,thisisdesignedforusebytheOrlovblockallocator.Thenewerfileallocationpolicies
oftheext2andext3filesystemsplacesubdirectoriesclosertogetherallowingfasteruseofadirectorytreeif
thatdirectorytreewascreatedwitha2.6kernel.

't'Afilewiththetattributewillnothaveapartialblockfragmentattheendofthefilemergedwithotherfiles
(forthosefilesystemswhichsupporttailmerging).ThisisnecessaryforapplicationssuchasLILOwhichread
thefilesystemsdirectly,andwhichdontunderstandtailmergedfiles.Note:Asofthiswriting,theext2orext3
filesystemsdonot(yet,exceptinveryexperimentalpatches)supporttailmerging.

'u'Whenafilewiththeuattributesetisdeleted,itscontentsaresaved.Thisallowstheusertoaskforits
undeletion.Thisisanotherattributethatissupportedbyeverythingexceptthekernelitself.
Example:

#lsattrtestfile
testfile
#chattr+itestfile
#lsattrtestfile
itestfile
#rmftestfile
rm:cannotremove`testfile':Operationnotpermitted
#chattritestfile
#rmftestfile
#lstestfile
ls:testfile:Nosuchfileordirectory
____________________________________________________________________________________________________________

Page58

LinuxITTechnicalTrainingCentre

TheLinuxFilesystem

_________________________________________________

____________________________________________________________________________________________________________

Page59

LinuxITTechnicalTrainingCentre

TheLinuxFilesystem

_________________________________________________

5.ExercisesandSummary
ReviewQuestions(answersp.165)
YesorNo
1.The/usrdirectorymustalwaysbeontherootdevicesinceitcontains
essentialtoolsneededatboottime

_____

2.Ifauser'shomedirectoryisanywhereelsethaninthe/homedirectory
thensomeoperationsmaynotwork

_____

3.Makingafilesystemonapartitionalwaysdeletesallthedataonthatpartition

_____

Glossary
Term

Description

basedirectories

subdirectoriesthataredirectlyundertherootdirectory

datablock

blockusedtostoredataonafilesystem.Datablocksarereferencedbyinodes

essentialroot(/)
subdirectories

termusedinthismanualtoidentifydirectoriesthatmustbepresentatboottimeonce
therootfilesystemhasbeenmounted

ext2

thesecondextendedfilesytemtypewasadoptedasthegenericLinuxfilesystem

ext3

thethirdextendedfilesystemsupportsthesamefeaturesasext2withanadded
journallingsystem

filepermissions

attributesstoredinsideafile'sinodegivingsimpleread,writeandexecutepermissions
tothefileowner(u),thegroup(g)andanyother(o)useraswellasmoreadvanced
permissionssuchasSUID,SGIDandthe'stickybit'

filesystemhierarchy "Thisstandardconsistsofasetofrequirementsandguidelinesforfileanddirectory
standard(FHS)
placementunderUNIXlikeoperatingsystems.Theguidelinesareintendedtosupport
interoperabilityofapplications,systemadministrationtools,developmenttools,and
scriptsaswellasgreateruniformityofdocumentationforthesesystems"see
http://www.pathname.com/fhs/
inode

blockusedtostoreinformationaboutfiles,directoriesandsymboliclinks.Information
includesthelocationofthefile'sdatablock,filepermissions,timestampsandfiletype
(e.gdirectory,fileorsymlink)

Orlovblockallocator SchemethatincreasestheperformanceofanEXT2/EXT3filesystem.Itisonly
availablefor2.6kernels.ItwasportedfromBSDandimprovedbyAlexanderViro,
AndrewMorton,andTedTs'o.TheoriginalauthorisGrigoryOrlov.Thisschemecan
beswitchedonandofusingthechattrcommandunderLinux
superblock

isreadwhenthefilesystemismounted,containsinformationsuchastheblocksize
usedforthecurrentfilesystem(default1024),thenumberoffreeinodes,themount

____________________________________________________________________________________________________________

Page60

LinuxITTechnicalTrainingCentre

TheLinuxFilesystem

_________________________________________________
countandmaximummountcount(usedtodetermineifafullfilesystemcheckshould
beperformed)

Files
File

Description

/etc/mtab

fileusedbymounttokeeptrackofcurrentlymounteddevices

/proc/mounts

fileusedbythekerneltokeeptrackofcurrentlymounteddevices

Commands
Command

Description(apropos)

chattr

changesfileattributesonaext2/3filesystem

chgrp

chgrpchangethegroupownershipofafile

chmod

chmodchangefileaccesspermission

chown

chown(1)changetheuserandgroupownershipofafile

df

dfreportfilesystemdiskspaceusage

du

duestimatefilespaceusage

e2fsck

e2fsckcheckandrepairaLinuxsecondextendedfilesystem

fsck

checkandrepairanyfilesystem

lsattr

liststhefileattributesonaext2/3filesystem

mke2fs

mke2fscreateanext2/3filesystem

mkfs

mkfsbuildaLinuxfilesystem

mount

mount(1)AllfilesaccessibleinaUnixsystemarearrangedinonebigtree,thefile
hierarchy,rootedat/.Thesefilescanbespreadoutoverseveraldevices.Themount
commandservestoattachthefilesystemfoundonsomedevicetothebigfiletree.
Conversely,theumount(8)commandwilldetachitagain

umask

toolusedtosetthefilecreationmaskmodeseehelpumask

Filesystem
1.

Create2newpartitions(largerthan50M)onthe/dev/hdadeviceusingfdisk.
HINT:Tocreateanewpartitiontypen.Thepartitiontypedefaultsto83(Linux)
Towritethenewpartitiontabletypew.
Thepartitiontableneedstoberead:REBOOTthecomputer!

2.

Formatthefirstpartitionusingtheext2filesystemtypeandthesecondwithreiserfs.

____________________________________________________________________________________________________________

Page61

LinuxITTechnicalTrainingCentre

TheLinuxFilesystem

_________________________________________________
HINT:Themkfstoolisafrontformkfs.ext2ormkfs.reiserfs,etc.Thesyntaxis
mkfst<fstype><device>
3.

Makedirectoriesin/mntandmountthenewpartitions
mkdir /mnt/ext2
mkdir /mnt/reiserfs

4.

Checkthestatusofyoursystem:
Usemounttoverifywhichdevicesaremounted.Thepermissionssetinfstabarevisibletoo.
Usedftocheckthetotalnumberofblocksused.Thekoptionwillconvertthenumberofblocksin
kilobytes(thedefaultblocksizeforext2)

Runfsckononeofthenewlycreatedfilesystems.Thefsckutilityisafrontforfsck.ext2,fsck.ext3,
fsck.reiserfs,etc.Thesyntaxis:
fsck
5.

<device>

Goingfurther:Changingfromext2toext3:
Updatethedevicemountedon/mnt/ext2toext3withtune2fs.Thiswilladdajournaltotheexisting
filsystem.Makesuretomaketherelevantchangeforthefilesystemtypein/etc/fstab
tune2fsj/dev/hdaN

Atthisstagethesystemhasaddedajournaltothe/dev/hda10partition,makingitanext3formated
partition.Thisprocessisnondestructiveandreversible.Ifyoumountanext3asanext2filesystem,the
.journalfilewillbeerased.Youcanadditagainwithtune2fs
Filepermissions
1.
664.

Loginasauser(nonroot).Createafileusingtouchandverifythatithastheeffectivepermission

2.

Changetheumaskto027.Ifyoucreateanewfilewhatisitseffectivepermission?_________
Whereisthevalueofumaskset?Depeningthesystemsthiscanbe/etc/profileor/etc/bashrc

3.

Add2userstoyoursystem.
useradd user1
useradd user2

Addpassordswith passwd user1 and passwd user2


4.

Createagroupcalledsales.

____________________________________________________________________________________________________________

Page62

LinuxITTechnicalTrainingCentre

TheLinuxFilesystem

_________________________________________________
groupadd sales
5.

Addtheuserstothegroupsales
gpasswd -a user1 sales
gpasswd -a user2 sales

6.

Createadirectory/newsownedbythegroupsalesandreadwritableforthisgroup.
mkdir -m 770 /news ; chown .sales /news

7.

SettheGIDtothe/newsdirectory.
chmod g+s /news
Whatarethesymbolicpermissions(eg.rwxr_xr_x)on/news?[usels -ld /news]______

Verifythatagroupmemberdoesntneedtotypenewgrpsalesinordertocreatefileswiththeright
permissions.Canmembersofthegroupsalesmodifyanyfilesinthisdirectory?

8.

Addthestickybitpermissiononthe/newsdirectory.Verifythatonlyuserownerscanmodifythefiles
inthethatdirectory.Whatarethepermissionslikeon/news?______________

10.

AsrootsetSUIDrootxeyes.Loginasanonrootuser.CheckthatthisbinaryrunswithUIroot.
chmod u+s `which xeyes`
Loginasanotheruserandrunxeyes.Thendo:
ps aux | grep xeyes
(thebinaryshouldberunningasroot)

____________________________________________________________________________________________________________

Page63

LinuxITTechnicalTrainingCentre

TheCommandLine

_______________________________________________

TheCommandLine
Prerequisites
None

Goals
Introducethebashshellandbasicconceptssuchasinteractivelystartinganexecutable
Distinguishvariablesdefinedaslocalorglobal(exported)
Manipulatedatastreamsusingpipesandotherredirectionoperators
Understandmetacharactersusedfor"fileglobbing"

Contents
THECOMMANDLINE............................................................................................................. 56
1.Theinteractiveshell..................................................................................................................... 57
2.Variables...................................................................................................................................... 58
3.Input,Output,Redirection............................................................................................................ 59
4.MetacharactersandQuotes........................................................................................................ 62
5.TheCommandHistory................................................................................................................. 63
6.OtherCommands........................................................................................................................ 64
7.ExerciseandSummary................................................................................................................ 67

________________________________________________________________________________________________________

Page64

LinuxITTechnicalTrainingCentre

TheCommandLine

_______________________________________________
Overview
Abasicwaytointeractwithacomputersystemistousethecommandline.Theshellinterprets
theinstructionstypedinatthekeyboard.Theshellprompt(endingwith$or#foruserroot)
indicatesthatitisreadyforuserinput.
Theshellisalsoaprogrammingenvironmentwhichcanbeusedtoperformautomatedtasks.
Shellprogramsarecalledscripts.
MostCommonshells
TheBourneshell

/bin/sh

TheBourneagain
shell

/bin/bash

TheKornshell

/bin/ksh

TheCshell

/bin/csh

Tom'sCshell

/bin/tcsh

SincethebashshellisoneofthemostwidelyusedshellsintheLinuxworldtheLPI
concentratesmainlyonthisshell.

1.Theinteractiveshell
Shellcommandsareoftenoftheform
command [options] {arguments}.
Printingtexttothescreen
Thethebashshellusestheechocommandtoprinttexttothescreen.
echothisisashortline

Full/Relativepath
Theshellinterpretsthefirstwordofanystringgivenonthecommandlineasacommand.Ifthestringis
afullorrelativepathtoanexecutablethentheexecutableisstarted.Ifthefirstwordhasno/
characters,thentheshellwillscandirectoriesdefinedinthePATHvariableandattempttorunthefirst
commandmatchingthestring.
ForexampleifthePATHvariableonlycontainsthedirectories/binand/usr/binthenthestringxeyes
won'tbefoundsinceitisstoredin/usr/X11R6/bin/xeyessothefullpathneedstoberun
/usr/X11R6/bin/xeyes

________________________________________________________________________________________________________

Page65

LinuxITTechnicalTrainingCentre

TheCommandLine

_______________________________________________
Analternativetotypingthefullpathtoanexecutableistousearelativepath.Forexample,iftheuseris
inthedirectorywherethexeyesprogramisstoredthenonecantype
./xeyes

2.Variables
Shellvariablesaresimilartovariablesusedinanycomputinglanguage.Variablenamesarelimitedto
alphanumericcharacters.ForexampleCREDIT=300simplyassignsthevalue300tothevariablenamed
CREDIT.

1.initialiseavariable:

VariableName=value(nospaces!!)

2.referenceavariable:

$VariableName

CREDIT=300
echo$CREDIT
Thevalueofavariablecanberemovedwiththeunsetcommand.

Export,SetandEnv:
Therearetwotypesofvariable:localandexported.
Localvariableswillbeaccessibleonlytothecurrentshell.Ontheotherhand,exportedvariablesare
accessiblebyboththeshellandanychildprocessstartedfromthatshell.
Thecommandssetandenvareusedtolistdefinedvariables

Thesetandenvcommands
set

Listsallvariables

env

Listsallexportedvariables

Aglobalvariableisglobalinthesensethatanychildprocesscanreferenceit.

LOCAL

parent

EXPORTED

child

child
parent

VAR=??

VAR=val

________________________________________________________________________________________________________

exportVAR=val
Page66

LinuxITTechnicalTrainingCentre

TheCommandLine

_______________________________________________
LOCAL

EXPORTED

VAR=val

Example:MaketheCREDITvariableaglobalvariable.Testwhetherit'slistedwithsetorenv.
exportCREDIT
env|grepCREDIT

Startanewshell(childprocess)andverifythatCREDITisaccessible.Canonestartanyshellandbe
surethatCREDITisstilldeclared?
Listofcommonpredefinedvariables
MEANING

PREDEFINEDVARIABLES
DISPLAY

UsedbyXtoidentifywheretorunaclientapplication

HISTFILE

Pathtotheusers.bash_historyfile

HOME

Thepathtotheuser'shome

LOGNAME

Thenameusedbytheusertologin

PATH

Listofdirectoriessearchedbytheshellforprogramstobe
executedwhenacommandisenteredwithoutapath.

PWD

Thecurrentworkingdirectory

SHELL

Theshellused(bashinmostLinuxdistributions)

TERM

Thecurrentterminalemulation

Specialvariables
Thenextfewvariablesarerelatedtoprocessmanagement.
$!
$$
$?

representsthePIDvalueofthelastchildprocess
representsthePIDoftherunningshell
is0ifthelastcommandwasexecutedsuccessfullyand1otherwise

3.Input,Output,Redirection
UNIXprocessesnormallyopenthreestandardfiledescriptorswhichenableittoprocessinputand
output.Thesestandarddescriptorscanberedefinedforanygivenprocess.Inmostcasesthestdin
descriptoristhekeyboard,andthetwooutputdescriptors,stdoutandstderr,isthescreen.
________________________________________________________________________________________________________

Page67

LinuxITTechnicalTrainingCentre

TheCommandLine

_______________________________________________
Aprocessandits3descriptors

STDIN
<

STDOUT
>
>>
STDERR |
2>

Numericalvaluesforstdin,stderrandstdout
0
stdin
1
stdout
2
stderr

stdoutredirection
program>file

Thedataflowsfromlefttoright.
fdiskl>partions.txt

Thiswillrunthefdiskutilityandoutputtheresulttothepartitions.txtfile.Nooutputisvisible.Alsonotice
thattheshellwillreadthislinefromtheright.Asaresult,the
partitions.txtfilewillbecreatedfirstifitdoesntexistandoverwrittenifthe>operatorisused.

The>>operatorwillappendstandardoutputtoafile.

STDOUTRedirection

process

>
>>

FILE/
DEVICE

1>

________________________________________________________________________________________________________

Page68

LinuxITTechnicalTrainingCentre

TheCommandLine

_______________________________________________
stdinredirection
program<file

Inthiscasedataflowsfromrighttoleft.The<operatorisonlyusedforstdinandcannotbeusedfor
stdout.
Ifthefileinstuctionscontainsoneachlinethelettersp,m,andqthenthenextexamplewouldcause
fdisktoprintthepartitiontableof/dev/hda,printtheutilityshelpscreenandfinallyquit:

fdisk/dev/hda<instructions

STDINRedirection

process

<

FILE/
DEVICE

0<

stderrredirection
program2>errorfile
stdin,stdoutandstderrarerepresentedby0,1and2respectively.Thisallowsonetoselectthestderr
stream:

find/2>/dev/null

STDERRRedirection

process

2>

FILE/
DEVICE

________________________________________________________________________________________________________

Page69

LinuxITTechnicalTrainingCentre

TheCommandLine

_______________________________________________
pipedcommands
program1|program2
Pipesarerepresentedbythe|symbol.Thedatastreamgoesfromthelefttotheright.Thenextfigure
illustrateshowthestdoutforoneprocessisredirectedtothestdinforanotherprocess.

PipedCommands

process

process

cat/var/log/messages|less

NBMultipleoutputredirectsareparsedfromrighttoleft,sothefollowingcommandsarenotequivalent.
Docommand2>&1>logfile
Docommand>logfile2>&1

TheteeCommand
command|teeFILENAME

Thiscommandisusedafterapipeandtakesafilenameasanargument.Thestandardoutputfromthe
previouscommandisthensenttothefilegivenasanargumentbutteealsoletsthestreamthroughto
stdout.Thestdouthasbeenduplicatedinthisway.

4.MetacharactersandQuotes
Metacharactersarecharactersthathavespecialmeaningfortheshell.Theyaremainlyusedforfile
globbing,thatistomatchseveralfilesordirectorynamesusingaminimumofletters.

Theinput(<),output(>)andpipe(|)charactersarealsospecialcharactersaswellasthedollar($)sign
usedforvariables.Wewillnotlistthemherebutnotethatthesecharactersareseldomusedtoname
regularfiles.
________________________________________________________________________________________________________

Page70

LinuxITTechnicalTrainingCentre

TheCommandLine

_______________________________________________

Wildcards

The*wildcardcanreplaceanynumberofcharacters.

ls/usr/bin/b*listsallprogramsstartingwitha'b'
The?wildcardreplacesanyonecharacter.
ls/usr/bin/?b*listsallprogramshavinga'b'asthesecondletter

[]isusedtodefinearangeofvalue.
lsa[09]listsallfilesstartingwithan'a'andhaveadigitinsecondposition.Also
ls[!Aa]*listsallfilesthatdon'tstartwithan'a'oran'A'
{string1,string2};althoughnotjustafilenamingwildcard,itcanbeusedtomatchthenamesof
existingfiles.
lsindex.{htm,html}

Quotesandescapecodes
Thespecialmeaningofmetacharacterscanbecancelledbyescapecharacters,whicharealso
metacharacters.
Thebackslash(\)iscalledtheescapecharacterandcancelsthemeaningofallmetacharactersforcing
theshelltointerpretthemliterally.
Thesinglequotes('')cancelthemeaningofallmetacharactersexceptthebackslash.

Thedoublequotes("")aretheweakestquotesbutcancelmostofthespecialmeaningoftheenclosed
charactersexceptthepipe(|),thebackslash(\)andavariable($var).

Thebacktick
Backquotes``willexecuteacommandenclosed.ThenextexampledefinesthevariableTIMEusingthe
datecommand.
TIME="Today'sdateis`date+%a:%d:%b`
echo$TIME
Today'sdateisSun:15:Jul

________________________________________________________________________________________________________

Page71

LinuxITTechnicalTrainingCentre

TheCommandLine

_______________________________________________
Anotherwayofexecutingcommands(similartothebackticks)istouse$().Thiswillexecutethe
enclosedcommandandtreatitasavariable.

TIME=$(date)

5.TheCommandHistory
Toviewthelistofpreviouslytypedcommandsyoucanusethebashbuiltincommandhistory.

history
1
ls
2
grep500/etc/passwd

Thishaslistedallthecachedcommandsaswellasthecommandssavein~/.bash_history.Whena
userexitstheshellcachedcommandsaresavedto~/.bash_history.
YoucanrecallcommandsbyusingtheUparrowandDownarrowonyourkeyboard.Therearealso
emacskeybindingsthatenableyoutoexecuteandevenedittheselines.
EmacsKeyBindingsforEditingtheCommandHistory
Ctrl+P

Previousline(sameasUparrow)

Ctrl+n

Nextline(sameasDownarrow)

Ctrl+b

Gobackonecharacterontheline(sameasLeftArrow)

Ctrl+f

Goforwardonecharacterontheline(SameasRightArrow)

Ctrl+a

Gotothebeginningoftheline(Sameas<Home>)

Ctrl+e

Gototheendoftheline(Sameas<End>)

Thebang!keycanbeusedtorerunacommand.

Example
!xexecutesthelatestcommandinthehistoryliststartingwithan'x'
!2runscommandnumber2fromthehistoryoutput
!2runsthecommandbeforelast
!!runsthelastcommand
^string1^string2runpreviouscommandandreplacestring1bystring2

________________________________________________________________________________________________________

Page72

LinuxITTechnicalTrainingCentre

TheCommandLine

_______________________________________________

6.OtherCommands
Aliases
Youcancreatealiasesforcommandsneedingmanyarguments.Theformattocreateanaliasis

alias myprog='command [options]{arguments}'

Bytypingaliasaloneatthecommandlineyouwillgetalistofcurrentlydefinedaliases.

Commandcompletion
BypressingTAB,theshellwillcompletethecommandsyouhavestartedtypingin.

<<isaredirectionforEOF
Forexample
cat << stop

willacceptstandardinputuntilthekeyword'stop'isentered.

Compoundcommands
command1;command2;command3

Thethreecommandsareruninsequenceregardlessof
thesuccessofthepreviouscommand

command1&&command2&&command3

Eachcommandwillexecuteonlyifthepreviousexit
codeis0(success)

command1||comand2||command3

Thenextcommandwillexecuteonlyifthepreviousexit
codeisnot0(failure)

The''exec'command
Thiscommandisnotabinarybutratherispartoftheshell.Itisusedtostartothercommands.Ordinarily
ifacommandisexecuted,asubprocessisstarted.Iftheexeccommandisusedtoinitiatethenew
program,itreoccupiestheprocessusedtostartit.Itreplacesthecurrentshell(inascriptorthe
interactiveshell).
________________________________________________________________________________________________________

Page73

LinuxITTechnicalTrainingCentre

TheCommandLine

_______________________________________________
Whenthenewcommandterminates,controlisnotpassedbacktothecallingshell,butreturnstothe
processthatcalledtheshellusedtomaketheexeccall.

echo$$
414
$bash
$echo$$
455
$echohello
hello
$echo$$
455
$execechohello
hello
$echo$$
414
Theaboveshowscontrolfallingbacktothesecondshell(process455)afterastraightforwardechoand
thefirstshell(process414)usinganexec.
Manpagesandthewhatisdatabase

Themanpagesareorganisedinsections
NAME
thenameoftheitemfollowedbyashortonelinedescription.
SYNOPSYS
thesyntaxforthecommand
DESCRIPTION
alongerdescription
OPTIONS
areviewofallpossibleoptionsandtheirfunction
FILES
filesthatarerelatedtothecurrentitem(configurationfilesetc)
SEEALSO
othermanpagesrelatedtothecurrenttopic
Thesearethemainsectionsonecanexpecttofindinamanpage.
ThewhatisdatabasestorestheNAMEsectionofallthemanpagesonthesystem.Thisisdonethrough
adailycron.Thewhatisdatabasehasthefollowingtwoentries:

name(key)

one line description

Thesyntaxforwhatisis:
whatis <string>
TheoutputisthefullNAMEsectionofthemanpageswherestringmatchednamed(key)

Onecanalsousethemancommandtoquerythewhatisdatabase.Thesyntaxis
________________________________________________________________________________________________________

Page74

LinuxITTechnicalTrainingCentre

TheCommandLine

_______________________________________________
man -k <string>
Thiscommandissimilartoapropos.Unlikewhatisthiswillqueryboththenameandtheoneline
descriptionentriesofthedatabase.Ifthestringmatchesawordinanyofthesefieldstheabovequery
willreturnthefullNAMEsection.

Example:(thematchingstringhasbeenhighlighted)
whatis lilo
lilo

(8)

- install boot loader

lilo.conf [lilo]

(5)

- configuration file for lilo

man -k

lilo

grubby
elilo

(8)

- command line tool for configuring grub, lilo, and

lilo

(8)

- install boot loader

lilo.conf [lilo]

(5)

- configuration file for lilo

TheFHSrecommendsmanpagestobekeptin/usr/share/man.Howeveradditionallocationscanbe
searchedusingtheMANPATHenvironmentvariablesetin/etc/man.config.Eachdirectoryisfurther
dividedintosubdirectoriescorrespondingtomanpagesections.
ManpageSections
Section1

Informationonexecutables

Section2

Systemcalls,e.gmkdir(2)

Section3

Librarycalls,e.gstdio(3)

Section4

Devices(filesin/dev)

Section5

Configurationfilesandformats

Section6

Games

Section7

Macropackages

Section8

Administrationcommands

Section9

Kernelroutines

ToaccessaspecificsectionNonehastoenter:
man N command
Examples:
man mkdir
man 2 mkdir

________________________________________________________________________________________________________

Page75

LinuxITTechnicalTrainingCentre

TheCommandLine

_______________________________________________
man crontab
man 5 crontab

7.ExerciseandSummary
ReviewQuestions(answersp.165)

YesorNo
1.IfthePATHvariableisn'tproperlysetthenprogramscanbe
startedonlyifuserstypeintheexecutable'sfullorrelativepath

_____

2.TheSTDOUTfromaprocesscanbepipedintoafile

_____

3.Onceadatastreamhasgonethroughapipethatstreamis
generallynolongervisibleonSTDOUT

_____

4.Allthecommandsenteredattheshellarestoredinamysqldatabase

_____

Glossary

Term

Description

compoundcommands

severalcommandsgiveninasinglelineattheshellusingdelimiters.
Dependingonthedelimitertheshellwillexecutethecommandsdifferently
(p.73)

metacharacters

characterthatisnotinterpretedliterallybytheshellbuthasaddedmeaning

commandsubstitution

usetheoutputofacommandasavariable.Thisisdonebyenclosingthe
commandinbackticks``orroundbrackets$()
Forexamplels /home/$(whoami)willlistthecurrentuser'shome
directory

fileglobbing

termusedwhenhandlingmultiplefilenamesusingwildcards.Thename
comesfromtheglobsubprograminoldUNIXshellsusedtoexpandwild
cardsgivenonthecommandline

redirectionandpipes

operationsthatmanipulatedatastreamsandthefiledescriptorsofaprocess.
Aredirectioninvolvesaprocessandafile,whereasapipewillinvolveonly
processes

stderr,stdin,stdout

namesofthefiledescriptorsavailableforanyprocesstostreamerror
messages,readinputstreamsandwriteoutput(nonerror)streams

wildcards

thefollowing*,?,"{}"or"[ ]"metacharactersusedtomatchmorethan
onecharacterwhenworkingonthecommandline

________________________________________________________________________________________________________

Page76

LinuxITTechnicalTrainingCentre

TheCommandLine

_______________________________________________

Commands
Command

Description(orapropos)

alias

setanaliasforasingleorasequenceofcommands(seemanbuiltinsorhelpalias)

echo

printtexttoSTDOUT

env

listvariablesthathavebeenexported(seemanbuiltinsorhelpenv)

exec

Shellbuiltinusedtoexecutenewprogramsbutinsteadofstartinganewsubprocessit
replacesthecallingprocess

export

exportthevalueofavariabletotheenvironmentofsubsequentlyexecutedcommands
(seemanbuiltinsorhelpexport)

history

displaythecommandhistorylistwithlinenumbers(seemanbuiltinsorhelphistory)

tee

tee(1)readfromstandardinputandwriteto(both)standardoutputandfiles

set

listallvariablesintheenvironmentofthecurrentprocess(seealsomanbuiltinsand
helpset)

Exercises
WARNING:Youwillneedtheuuencodeanduudecodecommandsintheexercises.Thesecommands
areprovidedbythesharutilspackage.
Stdinstdoutstderr
Typethenextcommandsandrepresentthesequenceofexecution(ifpossible)usingdiagramssimilarto
theonesusedinthischapter.
ls /etc ; df > /tmp/out.1
(ls /etc ; df) > /tmp/out.2
find /etc -type f

2> /dev/null | sort

tr [a-z] [A-Z] < /etc/passwd | sort > /tmp/passwd.tmp


cat /tmp/passwd.tmp | tr [A-Z] [a-z]

CommandLine
________________________________________________________________________________________________________

Page77

LinuxITTechnicalTrainingCentre

TheCommandLine

_______________________________________________
1.Listallfilesin/usr/X11R6/binthatdon'tstartwithanx
ls /usr/X11R6/bin/[!x]*
2.Thecommandxtermhasthefollowingoptions:
bg<color>
setbackground
fg<color>
setforeground
e<command> executecommandinterminal
Setanewaliassuchthatthesucommandopensanewcolorxtermandpromptsforaroot
password.
alias su=xterm -bg orange -fg brown -e su - &
Wherewouldyoustorethisaliasonthesystem?___________

3.Youcanencodefilesusinguuencode.Theencodedfileisredirectedtostdout.
Forexample:uuencode/bin/bashsupershell>uufileencodes/bin/bashandwillproduceafilecalled
supershellwhenrunninguudecodeagainsttheuufile

Mailtheuuencoded/bin/bashtoalocaluser(forthisyoucaneitheruseuuencodeandapipe|,
orsavetheuuencodedoutputtoafileuufileanduseSTDINredirection<).
Splittheuuencodedfileinto5files:

uuencode/bin/bashsupershell>uufile
splitb150000uufilebasename.

Thiswillcreatefilescalledbasename.aa,basename.ab,etc
Togetauuencodedfilewithalltheoriginaldata(unsplit)do
catbasename.*>uufile.new
Finallyuudecodethefileandcheckitstillworks.

uudecodeuufile.new
Thisshouldcreateabinaryfilecalledsupershell
3.WhichtoolfindsthefullpathtoabinarybyscanningthePATHvariable?_____
Variables
1.Dothefollowing
AssignthevaluevirustothevariableALERT.
ALERT=virus
Verifythatitisdefinedusingthesetcommand:
________________________________________________________________________________________________________

Page78

LinuxITTechnicalTrainingCentre

TheCommandLine

_______________________________________________
set |grep ALERT
IsALERTlistedwhenusingenvinsteadofset?

Nexttypebash.CanyouaccesstheALERTvariable?
bash
echo $ALERT
NOTEthevalueofALERT:______(isitblank?)
Typeexit(or^D)toreturntoyouroriginalsession.
UsetheexportcommandtomakeALERTaglobalvariable.
export ALERT
Verifythatitisaglobal(env)variable
env | grep ALERT
(v) StartanewbashshellandmakesurethatALERTisdefinedinthenewshell:
bash
echo $ALERT
Inthisnewshell,redefinethevariableALERT
export ALERT=green

Exitthatshell.WhatisthevalueofALERTintheoriginalshell?________

2.Atthecommandprompttypethefollowinglines:
CREDIT01=300;CREDIT02=400
forVARinCREDIT01CREDIT02;doecho$VAR;done
NoticethatthevariableVARisreferencedwith$VAR.

(i)Rerunthiscommand.
(ii)RerunthiscommandreplacingCREDIT01by$CREDIT01
3.UsingappropriatequoteschangeyourPS1variabletoincludethefullpathtoyourworkingdirectory.
(Hint:thevalueofPS1is[\u@\W]\$,youonlyneedtoreplacethe\Wbya\w)
PS1='[\u@\h \w ]\$ '
WhatdoesPS2looklike?________
________________________________________________________________________________________________________

Page79

LinuxITTechnicalTrainingCentre

FileManagement

_________________________________________________

FileManagement

Prerequisites
TheCommandLine(seep.64)
UnderstandtheEXT2filesystem(seep.48)

Goals
Effectivelymovearoundthefilesystemtocreate,deleteandfindfilesordirectories
Distinguishbetweenhardandsymboliclinks

Contents
FILEMANAGEMENT.................................................................................................................... 71
1.Movingaroundthefilesystem............................................................................................................. 72
2.FindingFilesandDirectories.............................................................................................................. 72
3.Handlingdirectories............................................................................................................................ 74
4.Usingcpandmv................................................................................................................................. 74
5.HardLinksandSymbolicLinks........................................................................................................... 75
7.Touchinganddding........................................................................................................................... 76
8.ExercisesandSummary..................................................................................................................... 78

________________________________________________________________________________________

Page80

LinuxITTechnicalTrainingCentre

FileManagement

_________________________________________________

1.Movingaroundthefilesystem
Absoluteandrelativepaths
Adirectoryorafilecanbeaccessedbygivingitsfullpathname,startingattheroot(/)oritsrelativepath,
startingfromthecurrentdirectory.
Absolutepath: independentoftheuser'scurrentdirectory
startswith/
Relativepath: dependsonwheretheuseris
doesn'tstartwith/
Asinanystructuredfilesystemthereareanumberofutilitiesthatcanhelpyounavigatethroughthesystem.
Thenexttwocommandsarebuiltincommands.

pwd:
cd:

Givesyouractualpositionasanabsolutepath.
The'changedirectory'command

2.FindingFilesandDirectories
Wewilldescribethefind,which,whereisandlocateutilities.

find
Syntax:
find <DIRECTORY> <CRITERIA> [-exec <COMMAND> {} \;]
TheDIRECTORYargumenttellsfindwheretostartsearchingandCRITERIAcanbethenameofafileor
directorywearelookingfor.
Examples:
find/usr/X11R6/binnamex*.
find/user502

Matchinglinesarelistedtostandardout.Thisoutputcanbeactedupon.Forexampledeletethefile,or
changethepermission.Thefindtoolhasthebuildinoptionexecwhichallowsyoutodothat.Forexample,
removeallfilesbelongingtouser502:

find/typefuser502execrmf{}\;

xargs
________________________________________________________________________________________

Page81

LinuxITTechnicalTrainingCentre

FileManagement

_________________________________________________
Thistoolisoftenthoughtofasacompaniontooltofind.Infactxargswillprocesseachlineofstandard
outputasanargumentforanothertool.Wecouldusexargstodeleteallfilesbelongingtoauserwith:

find/typefuser502|xargsrmf

Certaincommandssuchasrmcannotdealwithtoolongarguments.Itissometimesnecessaryto
deleteallfilesinadirectorywith
ls|xargsrmf

Commoncriteriaswitchesforfind
type
specifythetypeoffile
name
nameofthefile
user
userowner
atime,ctime,mtime
access,creationandmodifiedtimes(multiplesof24hrs)
amin,cmin,mmin
access,creationandmodifiedtimes(multiplesof1min)
newerFILE
filesnewerthanFILE

locate
Syntax:
locate <STRING>
Whenusinglocateallfilesanddirectoriesthatmatchtheexpressionarelisted.

locateX11R

Thesearchismuchfaster.Infactlocatequeriesthe/var/lib/slocate/slocate.dbdatabase.Thisdatabaseis
keptuptodateviaadailycronjobwhichrunsupdatedb.
Whenrunningupdatedbfromthecommandlinethe/etc/updatedb.conffileisreadtodeterminepruned
filessystems(e.gNFS)anddirectories(e.g/tmp)

which
Syntax:
which string
Thistoolwillreturnthefullpathtothefilecalledstringbyscanningthedirectoriesdefinedintheuser's
PATHvariableonly.Asaresultwhichisonlyusedtofindcommands.

whereis
Syntax
whereisstring
Thistoolwillreturnthefullpathtosourceorbinariesaswellasdocumentationfilesmatchingstringby
scanningthePATHvariableaswellasanumberofwellknownlocations
________________________________________________________________________________________

Page82

LinuxITTechnicalTrainingCentre

FileManagement

_________________________________________________
Gettingthemostfromls
Mostcommonoptionsforls
I
showinode
h
printhumanreadablesizes
n
listUIDsandGIDs
p
appenddescriptor(/=@)tolist
R
recursivelydisplaycontentofdirectories
S
sortbyfilesize
t
sortbymodificationtime(similartoc)
u
showlastaccesstime

3.Handlingdirectories
Makingadirectorywithmkdir:
Whenmakingadirectoryyoucansetthepermissionmodewiththemoption.Anotherusefuloptionisp
whichcreatesallsubdirectoriesautomaticallyasneeded.
Example:

mkdirpdocs/programs/versions

Removingdirectories:
Toremoveadirectoryuseeitherrmdirorrmr.Ifyouarerootyoumayhavetospecifyftoforcethe
deletionofallfiles.
Notice: rmrf/dir1/*removesallfilesandsubdirectoriesleavingdir1empty
rmrf/dir1/removesallfilesandsubdirectoriesincludingdir1

4.Usingcpandmv
cp
Syntax:
cp [options] file1 file2
cp [options] files directory
Itisimportanttonoticethatcpfile1file2makesanewcopyoffile1andleavesfile1unchanged.

Fig:file1withinode250iscopiedtofile2,duplicatingthedatatoanewdataareaandcreatinganewinode
6238forfile2

________________________________________________________________________________________

Page83

LinuxITTechnicalTrainingCentre

FileManagement

_________________________________________________
ID

250
ID
6238

Youcanalsocopyseveralfilestoadirectory,usingalistorwildcards.Thefollowingtableliststhemostused
options.
Mostcommonoptionsforcp
d
donotfollowsymboliclink(whenusedwithR)
f
force
I
interactive,promptbeforeoverwrite
p
preservefileattributes
R
recursivelycopydirectories
Note: cpr/dir/*/dir2/willcopyallfilesandsubdirectoriesomittingmydir
cpr/mydir//dir2/willcopyallfilesandsubdirectoriesincludingmydir

mv
Syntax:
mv [options] oldname newname
mv [options] source destination
mv [options] source directory
Themvcommandcanbothmoveandrenamefilesanddirectories.Ifoldnameisafileandnewnameisa
directorythenthefileoldnameismovedtothatdirectory.
Ifthesourceanddestinationareonthesamefilesystem,thenthefileisn'tcopiedbuttheinodeinformationis
updatedtospecifythenewlocation.Mostcommonoptionsarefforceoverwriteandiqueryinteractively.

5.HardLinksandSymbolicLinks
Symboliclinks
Asoftlinktoafileoradirectorycreatesanewinodethatpointstothesamedataarea:

lnslilo.conflilo.sym

________________________________________________________________________________________

Page84

LinuxITTechnicalTrainingCentre

FileManagement

_________________________________________________
Thisisthelistingforthesefiles.Noticethatthereferencecountis1forbothfiles.
rw1rootroot223Nov909:06lilo.conf
lrwxrwxrwx1rootroot9Nov909:06lilo.sym>lilo.conf

Fig2:Asoftlinktoafile

ID
lilo.conf

I
lilo.sym

Softlinkscanbecreatedacrossfilesystems.

HardLinks
Ahardlinkisanadditionalnameforthesameinodeandassuchthereferencecountofthefileincreasesby
oneforeverynewhardlink.

lnlilo.conflilo.link

Inthelistingnoticethatthereferencecountis2andthatbothfileshavethesamesize.Infacttheyare
identical.

rw2rootroot223Nov909:06lilo.conf
rw2rootroot223Nov909:06lilo.link

Hardlinkscanonlybecreatedwithinthesamefilesystem.

7.Touchinganddding
touch
________________________________________________________________________________________

Page85

LinuxITTechnicalTrainingCentre

FileManagement

_________________________________________________
Anotherwayofcreatingormodifyingafileistousetouch.
Syntax:

touch{options}file(s)

Iffiledoesn'texistitiscreated.Youcanalsochangetheaccesstimeofafileusingtheaoption,mchanges
themodificationtimeandrisusedtoapplythetimeattributesofanotherfile.

Example:
touchfile1.txtfile2.txt
touchmyfiler/etc/lilo.conf

createsnewfiles
myfilegetsthetimeattributesoflilo.conf

Tocreateafilecallederrorsusetheoption:
toucherrors

dd
ThiscommandcopiesafilewithachangeableI/Oblocksize.Itcanalsobeusedtoperformconversions
(similartotr).Mainoptionsareif=(inputfile)of=(outputfile)conv=(conversion)
Theconversionswitchcanbe:lcaseucaseascii
Example:
ddif=/mnt/cdrom/images/boot.imgof=/dev/fd0
Noticethatunlikecptheddtoolwillcopyportionsofadeviceandpreservetheunderlyingfilesystem.Onthe
otherhandcponlydealswiththedataandwilltransferitfromonefilesystemtoanother:

SOURCE

TARGET

cp:

dd:inputfile=device

outputfile=device

dd:inputfile=file

outputfile=device

________________________________________________________________________________________

Page86

LinuxITTechnicalTrainingCentre

FileManagement

_________________________________________________

dd:inputfile=device

outputfile=file

FilesystemA

FilesystemB

________________________________________________________________________________________

Page87

LinuxITTechnicalTrainingCentre

FileManagement

_________________________________________________

8.ExercisesandSummary
Review Questions(answersp.165)
YesorNo
1.Thecdcommandwilltakeyoubacktoapreviousdirectory?

_____

2.Typingcd~(inthebashshell)istheshortestcommandthatwilltake
youtoyourhomedirectory?

_____

3.Onecanmaketwonewdirectories/dir1/dir2usingmkdirwithoutanyoptions

_____

4.Thecommandupdatedbwillupdatethelocatedatabase

_____

5.ThesyntaxtocreateasymboliclinkcalledFILELINKpointingtothefileFILEis
ln -s FILE-LINK
FILE

_____

6.Thecommandscd/etcandcd./etcarealwaysequivalent

_____

Files
File

Description

/etc/updatedb.conf

configurationfilefortheupdatedbtool

/
thelocate(orslocate'securelocate')database
var/lib/slocate/slocate.db

Commands
Command

Description(apropos)

cd

changecurrentdirectoryseehelp cd

cp

cp(1)copyfilesanddirectories

dd

copyandconvertfiles.Oftenusedtocopythecontentofadiskdevicetoanotherdeviceorfile

find

find(1)searchforfilesinadirectoryhierarchy

ln

ln(1)makelinksbetweenfiles

locate

commandusedtosearchfilesanddirectoriesinthelocatedatabase

ls

ls(1)listdirectorycontents

mkdir

mkdir(1)makedirectories

mv

mv(1)move(rename)files

________________________________________________________________________________________

Page88

LinuxITTechnicalTrainingCentre

FileManagement

_________________________________________________
pwd

pwd(1)printnameofcurrent/workingdirectory

rm

rm(1)removefilesordirectories

touch

createnewemptyfileorchangefiletimestamps

updatedb

commandusedtoupdatethelocatedatabase

whereis

whereis(1)locatethebinary,source,andmanualpagefilesforacommand

which

which(1)showsthefullpathof(shell)commands

Exercises
FileNavigation
1.Makeanewdirectoryin/tmpcalled/etc.
mkdir /tmp/etc

2.In/tmp/etc/createafilecallednewfile(usetouch,catorvi).
3.Gototherootdirectory(cd/).
4.Testwhichofthefollowingcommandswillshowthecontentofnewfile?
cat etc/newfile
cat /etc/newfile
cat tmp/etc/newfile
cat /tmp/etc/newfile

5.Removethe/tmp/etcdirectorywithrmdir.Dostep1againthenremove/tmp/etcwithrm
Makingspaceonthefilesystem
Inordertocreatemorespaceonthedevicecontainingthedirectory/usr/share/docweneedtofindaspare
devicewithenoughspaceandcopythecontentsof/usr/share/doctothatdevice.Thenwecreatespaceby
deletingthe/usr/share/docdirectoryandcreatingasymboliclinkfrom/usr/share/doctothenewlocation.
6.Makeadirectorycalled/spareonwhichwewillmountasparedevices(oneofthepartitionscreatedin
thepreviousexercisesshouldbesuitable)
mkdir /spare
mount <device> /spare
7.Testwithdfh/spareandduhs/usr/share/docthatthedeviceislargeenoughtocontainallofthe
existingdata.
8.Next,copythecontentsof/usr/share/docto/spare/
cp -a /usr/share/doc /spare
9.Makesurethedatahasallbeencopiedacrossthenedit/etc/fstabtomakethatdeviceavailableatboot
time.
________________________________________________________________________________________

Page89

LinuxITTechnicalTrainingCentre

FileManagement

_________________________________________________
10.Delete/usr/share/docandcreateasymboliclinkpointingfrom/usr/share/docto/spare/doc
ln -s /spare/doc /usr/share/doc
11.(optional)Dothesamewith/home.Anyextraproblems?

FindingFilesontheSystem
12.Copythefile/etc/lilo.confto/etc/lilo.conf.bak
(i)Usefindtofindthisnewfile
(ii)Uselocatetofind/etc/lilo.conf.bak.
(iii)Updatethelocatedatabaseandretry(ii)

Backupstrategy(firststep)
Findallfilesinyourhomedirectorythathavebeenmodifiedinthepast24hours.
find/homemtime1|teelist1|wclines(1meanslessthanoneday)
WewillintroducearchivingtoolsinLPI102,buttheoutputofthefindcommandcanbepipeddirectlyinto
cpio.

________________________________________________________________________________________

Page90

LinuxITTechnicalTrainingCentre

ProcessManagement

_________________________________________________

ProcessManagement
Prerequisites
TheCommandLine(p.64)

Goals
FindtheprocessID(orPID)ofarunningprocessusingdifferenttools
Usekillandkillalleffectivelywiththeappropriatesignal
Managejobsfromthecommandlineintheforegroundorthebackground

Contents
PROCESSMANAGEMENT........................................................................................................... 81
1.Viewingrunningprocesses................................................................................................................. 82
2.ModifyingProcesses.......................................................................................................................... 83
3.Processesandtheshell..................................................................................................................... 85
4.ExercisesandSummary..................................................................................................................... 87

________________________________________________________________________________________

Page91

LinuxITTechnicalTrainingCentre

ProcessManagement

_________________________________________________

1.Viewingrunningprocesses
ProcesseshaveauniqueProcessIDthePID.Thisnumbercanbeusedtomodifyaprocess'priorityorto
stopit.
Aprocessisanyrunningexecutable.Ifprocess_2hasbeenspawnedbyprocess_1,itiscalledachild
process.Thespawningprocess_1iscalledtheparentprocess.
Theprocessfamilytree
Thepstreecommandgivesagoodillustrationofparentandchildprocesshierarchy.
Figure1:Partofthepstreeoutput
bash(1046)xinit(1085)+X(1086)
`xfwm(1094)+xfce(1100)xterm(1111)bash(1113)+pstree(1180)
||soffice.bin(1139)soffice.bin(1152)+
soffice.bin(1153)
|||soffice.bin(1154)
|||soffice.bin(1155)
|||soffice.bin(1156)
||`soffice.bin(1157)
|`xclock(1138)
|xfgnome(1109)
|xfpager(1108)
|xfsound(1107)
`xscreensaver(1098)

Intheabovefigurealltheprocess'PIDsareshown;theseareclearlyincremental.Themostcommonused
optionsareptodisplayPIDsandhtohighlightausersprocessesonly.

Findingrunningprocesses
Amoredirectwaytodeterminewhichprocessesarerunningistouseps.Mostusershaveasetcombination
ofoptionswhichworkformostsituations.

Herearethreesuchoptions:
________________________________________________________________________________________

Page92

LinuxITTechnicalTrainingCentre

ProcessManagement

_________________________________________________
psux
psT
psaux

allprocessesrunbytheuser
processesrununderthecurrentterminalbytheuser
allprocessesonthesystem

Itisrecommendedyoureadthepsmanpageandchooseyourownbestoptions!

psaccommodatesUNIXstyleandBSDstylearguments
usage:ps[Unix98options]
ps[BSDstyleoptions]
ps[GNUstylelongoptions]
pshelpforacommandsummary

Summaryofoptions
ashowallprocessesforthecurrentuserlinkedtoatty(exceptthesessionleader)
eorAshowallprocesses
fgivesthePPID(ParentProcessID)andtheSTIME(StartTime)
lissimilartofanddisplaysalonglist
ashowallprocesseslinkedtoatty,includingotherusers
xshowallprocesseswithoutacontrollingttyaswell

Continuouslyupdatingprocessinformation
Thetoputilitywillupdateinformationonprocessesatanadjustablerate.
Whiletopisrunningyoucantypehforalistofcommands.Thespacebarwillupdateinformationinstantly.
Youcanalsousetoptochangeaprocess'priorityasweshallseeinthenextsection.

2.ModifyingProcesses
Stoppingprocesses
Thekillcommandcanbeusedtosendsignalstoprocesses.Thereare63signalsavailable.Thedefault
signalterminatesaprocessandiscalledSIGTERMwithvalue15.
kill
Syntax
killSIGNALprocess_PID
________________________________________________________________________________________

Page93

LinuxITTechnicalTrainingCentre

ProcessManagement

_________________________________________________
EveryprocesscanchoosewhetherornottocatchasignalexceptfortheSIGKILLwhichisdealtwithbythe
kernel.MostdaemonsredifinetheSIGHUPtomeanrereadconfigurationfile.
MostCommonSignals
1orSIGHUPhangupordisconnecttheprocess
2orSIGINTsameasCtrl+Cinterrupt
3orSIGQUITquit
9orSIGKILLkilltheprocessthroughakernelcall
15orSIGTERMterminateaprocess'nicely'.ThisistheDEFAULTsignal.

Onecanalsostopprocesseswithoutknowingtheprocess'PIDusingkillall.

killall
Syntax
killallSIGNALprocess_NAME

Fig1:Interprocesssignaling

Processpriorityandnicenumbers
________________________________________________________________________________________

Page94

LinuxITTechnicalTrainingCentre

ProcessManagement

_________________________________________________
Nicenumbers(NI)altertheCPUpriorityandareusedtobalancetheCPUloadinamultiuserenvironment.
Eachprocessisstartedwithadefaultnicenumberof0.Nicenumbersrangefrom19[lowest]to20[highest].
Onlyrootcandecreasethenicenumberofaprocess.Sinceallprocessesstartwithadefaultnicenumberof
zeroasaconsequencenegativenicenumberscanonlybesetbyroot!

nicenumbersandCPUpriorities
19NI PRI
users
0(default)
root
20 Poolofprocesses 0

Tomodifyaprocess'prioritythatisalreadyrunninguserenice.Tosetaprocess'priorityusenice.
Syntax
nice<NI><process>
renice<+/NI>p<PID>
NoticethatreniceworkswithPIDsandhandleslistsofprocessesatatime.Ausefuloptiontoreniceisthe
uoptionwhichaffectsallprocessesrunbyauser.

Setnicenumber1forprocesses234and765:
renice+1p234765

Setnicenumber5forxclock:
nice5xclock

3.Processesandtheshell
backgroundandforgroundprocesses

________________________________________________________________________________________

Page95

LinuxITTechnicalTrainingCentre

ProcessManagement

_________________________________________________
Afteryouhavestartedaprocessfromtheshellyouautomaticallyleavetheshellinterpreter.Youwillnotice
thatnocommandswillrespond.Thereasonforthisisthatitispossibletorunprogramsintheforegroundfg
orinthebackgroundbgofashell.
Whenaprogramisrunningintheforegrounditispossibletorecovertheshellpromptbutonlybyinterrupting
theprogramforwhile.TheinterruptionsignalisCtrlZ.

Stoppingandstartingjobs
Aprocessstartedfromashellisalsocalledajob.Oncethejobreceivesthe^Zsignalitisstoppedandthe
shellpromptisrecovered.Torestarttheprograminthebackgroundsimpletype:bg.
Example
[mikelocalhost/bin]$xclock
xclockrunninginforground,shellpromptlost
[1]+Stoppedxclockxclockreceived^Zsignal
[mikelocalhost/bin]$bgshellpromptrecovered,issuethebgcommand
[1]+xclock&xclockisrunninginthebackground
[mikelocalhost/bin]$
Noticethe[1]+symbolabove.Theintegeristheprocess'jobnumber,whichitcanbereferredtoas.
The'+'signindicatesthelastmodifiedprocess.A''signwouldindicatethesecondlastmodifiedprocess.

Onecanstartaprocessinthebackgroundbyappendinga&tothecommand.

xclock&
[1]6213

Listingjobs
Thejobsutilitylistsallrunningprocessesstartedfromthecurrentshell.Thejobnumber,thejob'sstate
(running/stopped),aswellasthetwolastmodifiedprocesses,willbelisted.

Outputforjobs
[1]Stoppedxclock
[2]Runningxman&
[3]+Stoppedxload

________________________________________________________________________________________

Page96

LinuxITTechnicalTrainingCentre

ProcessManagement

_________________________________________________
Thejobnumber

Onecanconvenientlystopandstartaselectionofjobsusingthejobnumber.Thisisachievedwiththefg
command.
Callingjob2totheforegroundandkillingjob1
fg2or

kill9%1

fg%2or
fg%?xma

AvoidingHUPwithnohup
Finallythereisaprogramcallednohupwhichactsasaparentprocessindependentlyfromtheusers
session.Whenauserlogsoff,thesystemsendsaHUPtoallprocessesownedbythatprocessgroup.For
example,toavoidthisHUPsignalascriptcalledbigbangwhichattemptstocalculatetheageoftheUniverse
shouldbestartedlikethis:

nohupbigbang&

________________________________________________________________________________________

Page97

LinuxITTechnicalTrainingCentre

ProcessManagement

_________________________________________________

4.ExercisesandSummary
ReviewQuestions(answersp.165)
YesorNo
1.Runningkillagainstaprocesswillalwaysattempttokillthegivenprocess

_____

2.Thecommands'kill $(pidof xeyes 'and'killall xeyes'areequivalent

_____

3.Aprogramstartedwithapending'&'willruninthebackground

_____

4.Aprocess'snicenumberisthesameasitsCPUpriority

_____

Glossary
Term

Description

background aprocessstartedontheshellwith
process
$command &
Unlikeaforegroundprocesstheshelldoesn'tneedtowaitfortheprocesstoterminatebefore
runninganothercommand
foreground aprocessstartedontheshellwith
process
$command
Oncetheprocessisstartedtheshellhastowaitforittoterminatebeforeitcanrunanother
command
orphaned
process

aprocesswhoseparentprocesshasterminated.Anorphanedprocessisthen'adopted'by
init

PID

anumberassociatedwithaprocess

zombie
process

aprocessthathasexitedbutisstillconsideredbytheparentprocessaspresentuntilthenext
wait()systemcall.Thewait()systemcallperformedbytheparentprocessshouldrefresh
thestatusofthechildprocessasterminatediftheprocesshasexited.Azombieprocess
usuallydoesn'tlastforlong.Howeverduetobugssomezombieprocessescanlastlonger
takingupsystemresourceseventhoughtheprocessitselfhasphysicallyexited!

Commands
Command

Description(apropos)

bg

resumeasuspendedjobinthebackground

Ctrl+Z

keyboardcombinationusedtosuspendthecurrentforegroundprocess

________________________________________________________________________________________

Page98

LinuxITTechnicalTrainingCentre

ProcessManagement

_________________________________________________
fg

sendajobintheforeground(makingitthecurrentprocess)

jobs

listofprocessesstartedfromthecurrentshell

kill

sendaspecifiedsignaltoaprocessusingPIDs

killall

sendaspecifiedsignaltoaprocessusingprocessnames

nice

startsaprocesswithamodifiedschedulingpriority

nohup

nohup(1)runacommandimmunetohangups,withoutputtoanontty

ps

ps(1)givesasnapshotofthecurrentprocesses.Ifyouwantarepetitiveupdateofthis
status,usetop

pstree

printscurrentprocessesinahierarchicaltreerooted(bydefault)atinit

renice

modifiedschedulingpriorityofarunningprocess

top

top(1)displaytopCPUprocesses

Exercises
1.Checkthecurrentnicevalueofyourrunningxterminal.Changethisvalueusingtoporrenice.
2.Whatistheequivalentsignalofa^Zsenttoaprocess?(Listallsignalswithkilll)
3.Whichsignalisredefinedformostdaemonsandforcestheconfigurationfiletobereread?
4.Whatisthedefaultsignalsenttoaprocess,usingkillorkillall?
5.Whichsignalisdirectlyhandledbythekernelandcannotberedefined?
6.Makesureyoulogintoavirtualterminal(tty1totty6)beforedoingthis.Wewanttorunascriptthatwill
continuetorunoncewelogoutusingthenohupparentprocess.
Inthe/tmpdirectorycreateafilecalledprintoutwiththefollowingcontent:
count=0
while (true) do
echo this is iteration number $count
let count+=1
done
Wefirstdothefollowing(withoutusingnohup):
cd /tmp
./print-out &
exit
Youmaynotseethecommandlinewhentypingexitbutthisshouldlogyouout.Whenyoulogback
incheckthatprintoutisnolongerrunning
ps ux |

grep

print-out

________________________________________________________________________________________

Page99

LinuxITTechnicalTrainingCentre

ProcessManagement

_________________________________________________
Nextstartthecommandwith
nohup /tmp/print-out &
exit
Logbackinandtestthesecommands
ps ux |grep print-out
tail -f ~/nohup.out
Ctrl+C
killall print-out
ps ux|grep print-out
tail -f ~/nohup.out

________________________________________________________________________________________

Page100

LinuxITTechnicalTrainingCentre

TextProcessing

_________________________________________________

TextProcessing

Prerequisites
TheCommandLine(p.64)

Goals
Effectivelymanipulatefilesanddatastreamstoalterthecontentasrequired(e.gsortorformat)
Improvecommandlineskillsbymemorisingandunderstandingsimpletexttools

Contents
TEXTPROCESSING..................................................................................................................... 89
1.cattheSwissArmyKnife.................................................................................................................... 90
2.Simpletools........................................................................................................................................ 91
3.Manipulatingtext................................................................................................................................ 93
4.ExercisesandSummary..................................................................................................................... 96

________________________________________________________________________________________

Page101

LinuxITTechnicalTrainingCentre

TextProcessing

_________________________________________________

1.cattheSwissArmyKnife
cattheeditor

Thecatutilitycanbeusedasarudimentarytexteditor.

cat>shortmessage
wearecurious
tomeet
penguinsinPrague
Crtl+D

NoticetheuseofCtrl+D.Thiscommandisusedforendinginteractiveinput.

catthereader

Morecommonlycatisusedonlytoflushtexttostdout.Mostcommonoptionsare

nnumbereachlineofoutput
bnumberonlynonblankoutputlines
Ashowcarriagereturn

Example

cat/etc/resolv.conf
searchmydomain.org
nameserver127.0.0.1

tacreadsbacktofront

Thiscommandisthesameascatexceptthatthetextisreadfromthelastlinetothefirst.

tacshortmessage
penguinsinPrague
tomeet
wearecurious

________________________________________________________________________________________

Page102

LinuxITTechnicalTrainingCentre

TextProcessing

_________________________________________________

2.Simpletools
using

head

or
tail
Theutilitiesheadandtailareoftenusedtoanalyselogfiles.Bydefaulttheyoutput10linesoftext.Hereare
themainusages.

List20firstlinesof/var/log/messages:

headn20/var/log/messages
head20/var/log/messages

List20lastlinesof/etc/aliases:

tail20/etc/aliases

Thetailutilityhasanaddedoptionthatallowsonetolisttheendofatextstartingatagivenline.

Listtextstartingatline25in/var/log/messages:

tail+25/etc/log/messages

Exercise:Ifatexthas90lines,howwouldyouusetailandheadtolistlines50to65?Isthereonlyoneway
todothis?
Finallytailcancontinuouslyreadafileusingthefoption.Thisismostusefulwhenyouareexpectingafile
tobemodifiedinrealtime.

countinglines,wordsandbytes
Thewcutilitycountsthenumberofbytes,words,andlinesinfiles.Severaloptionsallowyoutocontrolwc's
output.
________________________________________________________________________________________

Page103

LinuxITTechnicalTrainingCentre

TextProcessing

_________________________________________________
Optionsforwc
countnumberoflines
l
countnumberofwords
w
countnumberofbytesorcharacters
corm
Remarks:
Withnoargumentwcwillcountwhatistypedinstdin.

numberinglines
Thenlutilityhasthesameoutputascatb.
Numberalllinesincludingblanks

nlba/etc/lilo.conf

Numberonlylineswithtext

nlbt/etc/lilo.conf

replacingtabswithspaces
TheexpandcommandisusedtoreplaceTABswithspaces.Onecanalsouseunexpandforthereverse
operations.

viewingbinaryfiles
Thereareanumberoftoolsavailableforthis.Themostcommononesareod(octaldump)andhexdump.

splittingfiles

Thesplittoolcansplitafileintosmallerfilesusingcriteriasuchassizeornumberoflines.Forexamplewe
canspilt/etc/passwdintosmallerfilescontaining5lineseach
________________________________________________________________________________________

Page104

LinuxITTechnicalTrainingCentre

TextProcessing

_________________________________________________

splitl5/etc/passwd
Thiswillcreatefilescalledxaa,xab,xac,xad...eachfilecontainsatleast5lines.Itispossibletogiveamore
meaningfulprefixnameforthefiles(otherthan'x')suchas'pass5.'onthecommandline

splitl5/etc/passwdpasswd5
Thishascreatedfilesidenticaltotheonesabove(aa,xab,xac,xad...)butthenamesarenowpasswd5aa,
passwd5ab,passwd5ac,passwd5ad...

Erasingconsecutiveduplicatelines
TheuniqtoolwillsendtoSTDOUTonlyoneversionofconsecutiveidenticallines.Considerthefollowing
example:

uniq>/tmp/UNIQUE
line1
line2
line2
line3
line3
line3
line1
^D
Thefile/tmp/UNIQUEhasthefollowingcontent:

cat/tmp/UNIQUE
line1
line2
line3
line1
NOTICE
Fromtheexampleaboveweseethatwhenusinguniqnonconsecutiveidenticallinesarestillprintedto
STDOUT.Whatisthecontentof/tmp/UNIQUEifwefirstsendtheSTDINthroughsort(seep.107)as
follows:
sort | uniq > /tmp/UNIQUE

________________________________________________________________________________________

Page105

LinuxITTechnicalTrainingCentre

TextProcessing

_________________________________________________

3.Manipulatingtext
Thefollowingtoolsmodifytextlayouts.
choosingfieldsandcharacterswithcut
Thecututililitycanextractarangeofcharactersorfieldsfromeachlineofatext.
Thecoptionisusedtomanipulatecharacters.
Syntax:
cutc{range1,range2}
Example

cutc510,15/etc/password

Theexampleaboveoutputscharacters5to10and15toendoflineforeachlinein/etc/password.
Onecanspecifythefielddelimiter(aspace,acommasetc...)ofafileaswellasthefieldstooutput.These
optionsaresetwiththedandfflagsrespectively.
Syntax:
cutd{delimiter}f{fields}

Example

cutd:f1,7outputdelimiter=""/etc/passwd
st
th
Thisoutputsfields1 and7 of/etc/passwddelimitedwithaspace.Thedefaultoutputdelimiteristhesame
astheoriginalinputdelimiter.Theoutputdelimiteroptionallowsyoutochangethis.

joiningandpastingtext
Theeasiestutilityispaste,whichconcatenatestwofilesnexttoeachother.
Syntax:
pastetext1text2

Withjoinyoucanfurtherspecifywhichfieldsyouareconsidering.
Syntax:
________________________________________________________________________________________

Page106

LinuxITTechnicalTrainingCentre

TextProcessing

_________________________________________________
joinj1{field_num}j2{field_num}text1text2or
join1{field_num}2{field_num}text1text2
Textissenttostdoutonlyifthespecifiedfieldsmatch.Comparisonisdoneonelineatatimeandassoonas
nomatchismadetheprocessisstoppedevenifmorematchesexistattheendofthefile.

sortingoutput
Bydefault,sortwillarrangeatextinalphabeticalorder.Toperformanumericalsortusethenoption.

formattingoutputwithfmtandpr
Youcanmodifythenumberofcharactersperlineofoutputusingfmt.Bydefaultfmtwillconcatenatelines
andoutput75characterlines.
fmtoptions
wnumberofcharactersperline
ssplitlonglinesbutdonotrefill
uplaceonespacebetweeneachwordandtwospacesattheendofasentence

Longfilescanbepaginatedtofitagivensizeofpaperwiththeprutility.Onecancontrolthepagelength
(defaultis66lines)andpagewidth(default72characters)aswellasthenumberofcolumns.
Whenoutputtingtexttomultiplecolumnseachcolumnwillbeevenlytruncatedacrossthedefinedpagewidth.
Thismeansthatcharactersaredroppedunlesstheoriginaltextiseditedtoavoidthis.

translatingcharacters
Thetrutilitytranslatesonesetofcharactersintoanother.

Examplechanginguppercaselettersintolowercase
tr'AB''ab'<file.txt

Replacingdelimitersin/etc/passwd:

tr':'''</etc/passwd

Notice:trhasonlytwoarguments!Thefileisnotanargument.
________________________________________________________________________________________

Page107

LinuxITTechnicalTrainingCentre

TextProcessing

_________________________________________________

4.ExercisesandSummary
ReviewQuestions(answersp.165)
YesorNo
1.Thecommands'cat FILE'and'cat < FILE'willbothdisplaythecontentsofFILE

_____

2.Thecommand'last FILE'willdisplaythe10lastlinesofFILE

_____

3.WhenalteringlinesfromafileusingcutthosechangesaremadeontheSTDOUTonly

_____

4.Whenrunninguniqagainstafileconsecutiveidenticallinesaredeletedinthefile

_____

Commands
Command

Description(apropos)

cat

cat(1)concatenatefilesandprintonthestandardoutput

cut

cut(1)removesectionsfromeachlineoffiles

expand

expand(1)converttabstospaces

fmt

fmt(1)simpleoptimaltextformatter

head

head(1)outputthefirstpartoffiles

join

join(1)joinlinesoftwofilesonacommonfield

nl

nl(1)numberlinesoffiles

od

od(1)dumpfilesinoctalandotherformats

paste

paste(1)mergelinesoffiles

sort

sort(1)sortlinesoftextfiles

split

split(1)splitafileintopieces

tac

tac(1)concatenateandprintfilesinreverse

tail

tail(1)outputthelastpartoffiles

tr

tr(1)translateordeletecharacters

unexpand

unexpand(1)convertspacestotabs

uniq

uniq(1)removeduplicatelinesfromasortedfile

wc

wc(1)printthenumberofbytes,words,andlinesinfiles

Exercises
1.Usecattoentertextintoafilecalledmessage.
________________________________________________________________________________________

Page108

LinuxITTechnicalTrainingCentre

TextProcessing

_________________________________________________
cat >> message
line 1
^D

DothesamebutusethekeywordSTOPinsteadofthepredefinedeofcontrol(^D).

cat >> message << STOP


line 2
STOP
Next,appendtexttomessageusingecho.
echo line 3 >> message
2.CreateafilecalledindexwithtwofieldsREFERENCEandTITLEseparatedbyaspace.
e.g
001
Using_Linux
CreateasecondfilepricingwithtwofieldsREFERENCEandPRICEseparatedbyaspace
e.g
001
9.99
Usejointodisplaythereference,titleandpricesfields.
3.Usingtrreplaceallcolonsbysemicolonsin/etc/passwd.
Dothesameusingcut.
4.Useheadandtailtolistlines70to85of/var/log/messages.

5.UsethecututilitytogetherwithgrepandifconfigtoprintoutonlytheIPaddressofthefirst
networkinterfaceeth0.
6.In/tmpmakeadirectorycalledfiles
mkdir /tmp/files
Create50filesinthatdirectory:
#!/bin/bash
count=0
while [ $count -lt 50 ]; do
touch /tmp/files/$count.txt
let count+=1
done
Wewanttochangeallthetxtextensionstodatextentions.Forthisweneedtotypethefollowingonthe
commandline:
for FILES in $(ls *.txt)
do
FILENAME=$(echo $FILES| cut -d. -f1)
mv

$FILES $FILENAME.dat

done

________________________________________________________________________________________

Page109

LinuxITTechnicalTrainingCentre

SoftwareInstallation

_________________________________________________

SoftwareInstallation
Prerequisites
TheCommandLine(p.64)

Goals
UnderstandtheuseofaMakefilewhencompilinglargeprojectsfromsource
Manipulatesourcearchiveseffectivelyandruntheappropriatebuildcommands
Fixproblemsrelatedtoshared(ordynamic)libraries
UsetheRPMpackagemanagertoquery,add,remove,updateorverifysoftware

Contents
SOFTWAREINSTALLATION........................................................................................................98
1.Introduction......................................................................................................................................... 99
2.StaticandSharedLibraries............................................................................................................ 100
3.SourceDistributionInstallation......................................................................................................... 104
4.TheRedHatPackageManagerRPM..............................................................................................107
5.DebianPackageManagement......................................................................................................... 112
6.TheAlienTool.................................................................................................................................. 116
7.ExercisesandSummary................................................................................................................... 117

________________________________________________________________________________________

Page110

LinuxITTechnicalTrainingCentre

SoftwareInstallation

_________________________________________________

1.Introduction
Webeginwithashortcodeexample.AlthoughwedontneedanadvancedunderstandingoftheClanguage,
theseexamplescanhelptroubleshootcommonsituations.

Themain.cfile:
#include<stdlib.h>
intmain(){
Hello();
}

TheHello.cfile:
#include<stdio.h>
voidHello(){
printf(Hi!\n);
}

Noticethatthemain.cisincompleteinthesensethattheHello()functionisundefined.Inthesameway
Hello.cdoesnthaveamaindeclaration.Sothesefilesareinterdependent.Onecanhowevercompile
objectfiles(.o)whicharelikenonexecutablebinaryfileswhichcanbeusedtobuildanapplication.

Compilingtheobjectfiles:

gcccmain.c
gcccHello.c

Thiswillgeneratetwofilesmain.oandHello.owhichcannowbeusedtobuildtheapplicationapp.

Compilingapp:

gccoappmain.oHello.o
Theooptionsimplyspecifiesanameforthecompiledcode.Ifnonameisspecifiedthecompiledoutputis
calleda.outbydefault.
________________________________________________________________________________________

Page111

LinuxITTechnicalTrainingCentre

SoftwareInstallation

_________________________________________________
AllthesestepscanbeautomatedusingaMakefile.HereisaminimalMakefilewhichwouldcompiletheapp
executable.

Makefile
SHELL=/bin/sh
CC=/usr/bin/gcc
app:main.oHello.o
$(CC)oappmain.oHello.o
main.o:main.c
$(CC)cmain.c
Hello.o:Hello.c
$(CC)cHello.c

2.StaticandSharedLibraries
Functionsthatwilloftenbeusedarearchivedaslibraries.Duringcompilationtheselibrariescanbelinkedto
thecodewhichusesthelibraryfunctioncalls.Thelibrarycaneitherbestaticallyordynamicallylinkedtothe
code.
Thegcccompilercanlinklibrariesinavarietyaways(manyoptions).Howeverbydefaultitwilllinkfilesthat
aregivenonthecommandlinethatdonthavea.cextention(onlythe.cfilesaretreatedascode).
Listing1:Linkingbydefault

gccmain.cHello.o

Thiswillproduceana.outexecutablewiththeHello.oobjectstaticallylinkedtoit.
Illustrationofastaticallylinkedapplication(a.out):

Hello.o

a.out

Staticlibraries
________________________________________________________________________________________

Page112

LinuxITTechnicalTrainingCentre

SoftwareInstallation

_________________________________________________
Staticlibrariesarearchived.ofiles.Thesearchivesarecreatedwiththeartoolandhavea.aextention.

Listing2:addinganobjectfiletoanarchive:

arrcslibfoo.afile1.ofile2.o

Dynamic/SharedLibraries
Asharedlibraryisalibrarythatwillbeloadedbytheprogramwhenitisexecuted.Onealsosaysthatthe
libraryisdynamicallyloaded.

Listing3:Creatingasharedlibrary:

gcccfPICHello.ccreatestheobjectfile
gccsharedW1,soname,libfoo.so.1olibfoo.so.1.0Hello.o

ThefPICflagenablesthePositionIndependentCodegeneration.

Listing4:Compilingwithasharedlibrary:

gccmain.clibfoo.so.1.0

Thiswillproduceana.outexecutable.Howeverifyoutrytorunthisitwillcomplainwiththeerrormessage
listedbelow.

Illustrationofadynamicallylinkedapplication(a.out):

libfoo.so

a.out

________________________________________________________________________________________

Page113

LinuxITTechnicalTrainingCentre

SoftwareInstallation

_________________________________________________
Theprocessofattachingadynamiclibraryatruntimeiscalledlinkingandishandledbytheld.solibrary.
Howdoesthelinkerknowwheretofindlibfoo.so?

Sharedlibrarynotfounderror:

./a.out:errorwhileloadingsharedlibraries:libfoo.so.1.0:cannotopen
sharedobjectfile:Nosuchfileordirectory

Thiserrorillustratesthecasewherethelinkercouldnotfindthedynamiclibrarylibfoo.so.1.0.Inthenext
sectionwewillseewhatcanbedonetofixthisproblem.

SharedLibrarynaminganddynamicloading
WewillusetheaboveexampletounderstandhowLinuxlibrariesaremaintained.

Figure1:TheSharedLibraryNames
Tofindoutwhichsharedlibrariesanexecutableneedsatexecutiontimethelddtoolisused.
Example:

ldda.out
libfoo.so.1.0=>notfound
libc.so.6=>/lib/libc.so.6(0x40028000)
/lib/ldlinux.so.2=>/lib/ldlinux.so.2(0x40000000)

________________________________________________________________________________________

Page114

LinuxITTechnicalTrainingCentre

SoftwareInstallation

_________________________________________________
Noticethatlibfoo.so.1.0isnotfound.Thisisbecausethea.outneedstodynamicallyloadthislibrary
andthedynamiclinkerld.soisnotawareofthisnewlibrary.
Infactthelinkerusesadatabasecalledtheldcachecontainingentriesoftheform:
soname=>/path/to/library

Thecontentoftheldcachecanbeviewedwiththefollowingcommand:

ldconfigp

libaudiofile.so.0 (libc6) => /usr/lib/libaudiofile.so.0


libaudiofile.so (libc6) => /usr/lib/libaudiofile.so
libaudio.so.2 (libc6) => /usr/X11R6/lib/libaudio.so.2
libattr.so (libc6) => /usr/lib/libattr.so

..........

Theldcacheisgeneratedatboottimebythesameldconfigtool.Bydefaultldconfigwillscanthe
directories/liband/usr/libtobuildtheldcache.
Iflibrariesareinstalledindifferentlocations(e.g/usr/local/lib,/opt/libor/usr/X11R6/lib)thesedirectories
needtobelistedin/etc/ld.so.confallowingldconfigtotakethesedirectoriesintoconsiderationwhen
buildingthecache.

Whathappenswhenanapplicationisstarted?
Theapplicationwillaskthelinkerforthedynamiclibrariesitneedsusingasoname,thelinkerwillthenquery
theldcacheandassociatethisnamewiththefullpathtotheactuallibrary.Oncethefullpathisknownthe
linkercanlinkthelibrarytotheapplication.

Whathappensiftheldcachedoesn'tcontainthefullpathtothelibrary?
Ingeneraltheapplicationwillfailtostartandwillprintanerrormessagesayingcannotopenshared
objectfile:Nosuchfileordirectory.Butonecanalsodefineaglobalvariablecalled
LD_LIBRARY_PATHandassigntothisvariablethenameofthedirectorycontainingthelibrary.

Knowingthiswecannowfixtheproblemwithourapplicationaboveusingoneofthetw0methodsbelow:
1.IfthebinaryneedstobetemporarytesteddefinetheLD_LIBRARY_PATHvariableasfollows:

export LD_LIBRARY_PATH=$(pwd)

________________________________________________________________________________________

Page115

LinuxITTechnicalTrainingCentre

SoftwareInstallation

_________________________________________________
2.Ifyouarerootandwouldlikethelibrarytobeavailableforallthencopythelibfoo.so.1.0fileto
/usr/local/lib/andrunldconfigtoupdatetheldcache.

TheGNUspecificationadviseslibrariestobestoredin/usr/local/lib.Theseguidelinesare
followedbydevelopersandmosttarballedcodewillinstalllibrariesinthatdirectoryandthebinaries
in/usr/local/bin.Installingandremovingthiscodefromthesystemwouldbedonebymake
installandmakeuninstall.

TheFHS(FilesystemHierarchyStandard)recommendslibrariesbekeptin/usr/lib/and
associatedbinariesin/usr/bin/.ThisconventionstandardisadheredtobyLinuxdistributions.
Ineffectmatureandstablecodeisstoredin/usr/ratherthan/usr/local/andthetwo
standardsdonotleadtoanycontradictions.Installingandremovingthiscodecodewouldbedone
usingtherpmcommand.

NOTICE
Withcertaindistributionsthe/usr/local/lib/directoryisnotscannedbyldconfig.Itissimplya
matterofaddingthisdirectoryto/etc/ld.so.confand...reboot?

3.SourceDistributionInstallation
Opensourceprojectsareoftendistributedastarballs(i.ecompressedtarredarchives).Manydevelopment
environments(glade,kdevelop)generatethefilesthathelpfacilitatecompilingandinstallationofaproject.

UncompressedArchives
Uncompressedarchiveshavea.tarextension.Forexampleifaprojecthasbeendevelopedinadirectory
calledmyprojetcv.1/thenthefollowingcommandwouldarchivethisdirectorywithallitsfilesand
subdirectories:

tar c my-project-v.1/ > my-project-v.1.tar


or

tar cf

my-project-v.1.tar my-project-v.1/

________________________________________________________________________________________

Page116

LinuxITTechnicalTrainingCentre

SoftwareInstallation

_________________________________________________
SincemostprojectsareverylargeandareavailablefordownloadfromtheInternettheyarerarely
uncompressed.

Compression
Thethreecompressiontoolscommonlyusedarecompress(old),gzipandbzip2.Unlikethewindowszip
thesecompressionscanonlybeappliedtofiles.Butsinceanarchiveisafilethatcontainsallthedata
neededtorecoverdirectories,thesecompressionsaresuitableforarchives.Acompressedarchiveisthen
calledatarball.
compressiontool

decompressiontool

catdecompression

fileextension

compress

uncompress

zcat

.Z

gzip

gunzip

zcat

.gz

bzip2

bunzip2

bzcat

.bz2

Examples

compress -v FILE1
FILE1:

-- replaced with FILE1.Z Compression: 40.29%

gzip
FILE2:

-v FILE2

53.4% -- replaced with FILE2.gz

bzip2 -v FILE3
FILE3:

2.326:1,

3.439 bits/byte, 57.01% saved, 605504 in, 260320 out.

NOTICE
1.Whencompressingafile,theoriginalfilenameisappendeda.Z,.gzor.bz2
2.Compressiontoolslistedaboveonlyworkonfilesandnotondirectories
3.Onlyonefileatatimecanbecompressed(nowildcards!)

Thezcatandbzcattoolscanbeusedtodecompressfiles,howeverthedecompressedfilewillbesentto
STDOUTsoitisnecessarytouseafileredirection:

zcat FILE1.Z > FILE1

________________________________________________________________________________________

Page117

LinuxITTechnicalTrainingCentre

SoftwareInstallation

_________________________________________________
ArchivesandCompression
compressiontool

tarswitch

archiveextension

compress

.tar.Zor.tgZ

gzip

.tar.gzor.tgz

bzip2

.tar.bz2

ThetableaboveintroducesthetaroptionsZ,zandjwhichcalltheappropriatecompressiontoolswhen
needed.

Thenexttwoexamplesareequivalent:

tar cf
bzip2

my-project-v.1.tar my-project-v.1/
my-project-v.1.tar

tar cjf

my-project-v.1.tar.bz2 my-project-v.1/

Workingwithtarballs
Weknowhowtocreatearchives.Allweneedisanoverviewofthemaintarswitches.
taroperations

Create

Extract

Test

minimalswitches

corcf

xf

tf

optionalswitches

v,Z,z,j

v,Z,z,j

v,Z,z,j

Examples(extractions)

tar xvjf myproject-v.1.tar.bz2


tar xzf some-other-project-v.2.0.tar.gz

Examples(tests)
________________________________________________________________________________________

Page118

LinuxITTechnicalTrainingCentre

SoftwareInstallation

_________________________________________________
tar tjf myproject-v.1.tar.bz2
tar tzf some-other-project-v.2.0.tar.gz

AlternativeExamples(usingzcatandbzcat)

bzcat myproject-v.1.tar.bz2 | tar xf zcat some-other-project-v.2.0.tar.gz | tar tf -

CommonFiles
Onceaprojecthasbeenextractedyoucanexpecttofindthefollowingfiles:

configure:Thisisascriptwhichdetermineswhatarchitectureisbeingused.Italsochecksthattherequired
compiler,librariesanheadersarepresent.ThisinformationisthenstoredinfilescalledMakefile
Thesafestwaytorunthescriptistouse./configure.
Youcanalsodecidewheretheprojectwillbeinstalledusingthe-prefixoption.Thedefaultinstallation
directoryformostprojectsis/usr/local.Ifyouwanttoinstallthecompiledprojectinyourhomedirectoryyou
shouldtype:

./configure prefix=$HOME

Makefile:Thisactslikeaconfigurationfileforthemakeutility.Themaininformationprovidedis:
Thenameofthecompilerandcompilingoptions
Thepathtothesharedlibrariesandheaderfiles
Mappingbetweencodefiles(.c)andobjectfiles(.o)

Compilingtheproject
Ifthefilesabovearepresentthenthereisagoodchancethatyouwillsuccessfullyporttheprogramtoyour
computer.Herearetheroutinesteps:

________________________________________________________________________________________

Page119

LinuxITTechnicalTrainingCentre

SoftwareInstallation

_________________________________________________
./configure
make
makeinstall

Itisstronglyrecommendedtorun./configureandmakeasanonrootuser.
makeinstallmustberunasrootonlyiftheinstallationdirectoriesarewriteprotected(/usr/or/usr/local).
Therearemanyoptionstothe./configurescript.Tocustomiseyourinstallationyoucouldtype
./configure -help

4.TheRedHatPackageManagerRPM
MostLinuxdistributionsmanagesoftwareusingsomeformofpackagemanagementtoperformtaskssuch
asinstallations,updatesandqueries.ThemostpopularpackagetypesareDebianandRPM.Weonlycover
RPMinthismanual.

TheFunctionsofaPackageManager

Packagenaming
________________________________________________________________________________________

Page120

LinuxITTechnicalTrainingCentre

SoftwareInstallation

_________________________________________________
Thereisnostrictconventionbutmostrpmpackagenamesareformedasfollows:
nameversionrelease.architecture.rpm
Thearchitecturenamecaneitherindicatewhichcomputerarchitecturetheenclosedbinariesaremadefor
(e.gi386,ppc,ia64,noarch)oritcanindicatethatthepackagecontainsthesourcecode(src).

Majorandminormodes
Someshortnameoptionsaresimilarbutperformdifferentactionsdependingontheirpositiononthe
commandline.Adistinctionismadebetweenthefirstoptionandotheroptions.

Thefirstoptiongiventorpmisinmajormode.Forexampleinrpm -iv A.rpmtheoption'i'isamajor


optionandwillcausepackageAtobeinstalled.
Similarlyanoptionthatisnotinfirstpositionisinminormode.Forexampleinrpm -qpi A.rpmtheoption'i'
isaminormodeandwillgetinformationfromthepackageAsuchastheauthorandthelicencetype.
Thesearethemajormodeoptionsforrpm.
Short
i
U
F
V
q
e

Long
install
update
freshen
verify
query
erase

Description
Installsthepackage
Updatesorinstallsapackage
Updatesonlyinstalledpackage
filesize,MD5,permissions,type...
Queriesinstalled/uninstalledpackages,andfiles
Uninstallpackage

Thesearetheminormodeoptionsforrpm.
Short
a
c
d
f
h
i
l
p
v

Description
appliestoallinstalledpackages
togetherwithqlistsconfigurationfiles
togetherwithqlistsdocumentationfiles
togetherwithqquerieswhichpackageinstalledagivenfile
addshasheswhileprocessing
togetherwithqlistsinformationaboutapackage
togetherwithqlistsallfilesanddirectoriesinapackage
togetherwithqspecifiesthatthequeryisperformedonthepackagefile
verbose

Querymodes
Threequerytypes:uninstalledpackages,installedpackagesandfiles
QueryType
Option
Packagefile
qp
Installedpackage
q
File
qf
________________________________________________________________________________________

Page121

LinuxITTechnicalTrainingCentre

SoftwareInstallation

_________________________________________________
Anextraoptionwillallowyoutogetinformationonallinstalledfilesl,documentationdconfigurationfiles
c,etc...

Weconsiderforexamplethepackagerouted0.17.i386.rpm.Wecanquerythispackageandlistitscontents
beforeinstallationwiththeloptionasfollows:

rpmqplrouted0.17.i386.rpm

Oncethispackageisinstallwecanquerytheinstalledpackagewith:

rpmqlrouted0.17
rpmqlrouted

or

Finallyifwewanttofindoutwhichpackageinstalledthefile/usr/sbin/routedtherpmdatabasecanbe
queriedwith:

rpmqf/usr/sbin/routed

SpecialOptions
nodeps
force
test
requiresPACKAGE
whatrequires CAPABILITY

installapackageregardlessofdependencies
forceanupgrade
doesntactuallyinstallorupgrade,justprintstostdout
togetherwithqlistscapabilitiesrequiredbyapackage
togetherwithqlistspackageswhichrequirethecapability

PackageSignatures
Youcancheckthesignatureofeachpackagethatisdistributedaspartofaproject.Forexampletoloadthe
keysofallthedevelopersinvolvedwiththeFedoraprojectdothefollowing(justonce):

rpmimport/usr/share/rhn/RPMGPGKEYfedora

________________________________________________________________________________________

Page122

LinuxITTechnicalTrainingCentre

SoftwareInstallation

_________________________________________________
YoucannowdownloadanypackagefromanFTPsitewhichmirrorstheproject'sRPMs.Forexamplewe
downloadedzlib1.2.1.12.1.i386.rpmfromftp.mirror.ac.ukintheFedorasubdirectory.Wenextcheckthe
authenticityofthefile:

rpmchecksig/home/adrian/zlib1.2.1.12.1.i386.rpm
/home/adrian/zlib1.2.1.12.1.i386.rpm:(sha1)dsasha1md5gpgOK

PackageIntegrity
Thenextcommandcheckstheintegrityofthepackagebash:

rpmVbash
Thisreturnsnothing.Wenextdothefollowingasuserroot:

chownbin/bin/bash

chmod775/bin/bash
Ifwechecktheintegrityofbashagainthistimeweget:

rpmVbash
.M...U../bin/bash
Thepackagemanagerhascomparedthecurrentstatusofallfileswhicharepartofthebashpackagewith
theknownoriginalstateofthesefilesstoredinadatabase.Thechangesmadeto/bin/bashhavebeen
identified.
Itispossibletoverifytheintegrityofallpackagesinstalledonthesystembyaddingthe'a'(all)option
after'V'(verify)
Theverifyoptionperformsanumberoftestsoneachfile;whenatestispositiveanumberofcharacters
(listedbelow)areusedtoidentifytheerrors:

Returnedcharacter

Errordescription

thetestwassuccessful

thetestcouldn'tbeperformed

________________________________________________________________________________________

Page123

LinuxITTechnicalTrainingCentre

SoftwareInstallation

_________________________________________________
S

filesizehaschanged

permissionmodeorfiletypehaschanged

thefile'sMD5sumhaschanged

devicemajor/minornumbermissmatch

brokensymboliclink

theuserownerofthefilehaschanged

thegroupownerofthefilehaschanged

themtime(modifiedtime)haschanged

GoingFurther:BuildingRPMpackages(notforLPIexampurpose)
NOTICE:
Thisisadditionalinformation,thisparagraphisnotanLPI101objective.Whendoingthissectionyoumay
encounterproblemswiththerebuildoption,thisisduetothefactthatthenewversionsofRPMuse
rpmbuildinsteadofrpmwhenrebuildingpackages.
ThesourcecodeformanyRPMpackagesisalsoavailableasanRPMpackageandwillbeusedtobuilda
binarypackage.Thenamingconventionis:
nameversionrelease.src.rpm
Thesepackagescontainatleasttwofiles,thetarballwiththecodeandaspecfile.Thespecfilecontains
instructionstopatch,compileandbuildtheRPMpackage.Ifthecodeneedstobepatchedbeforecompilation
thenthepatchesareincludedinthesourcepackage.
TherearethreedifferentwaystobuildaRPMpackage.Wewillassumethatwehaveapackagecalled
nameversionrelease.src.rpm.
Forthesemethodstoworkyoufirstneedtoinstalltherpmbuildpackage
Method1:
InstalltheRPMsourcepackagewith:
rpmivhnameversionrelease.src.rpm

Thiswillcopyfilestothefollowingdirectories:
/usr/src/redhat/SPECS
/usr/src/redhat/SOURCES
________________________________________________________________________________________

Page124

LinuxITTechnicalTrainingCentre

SoftwareInstallation

_________________________________________________

Inthe/usr/src/redhat/SPECSdirectorythereisnowafilecalledname.spec(wherenameisthename
ofthepackage).Tostartbuildingthecompiledpackage,thatisnameversionrelease.i386.rpm,wetypein
thefollowingcommand:
rpmbaname.spec

Thiswillstartaseriesofscripts.Thetarballin/usr/src/redhat/SOURCESwillbeunpackedin
/usr/src/redhat/BUILD.
Ifthecompilationsucceedsthenthebuiltbinarypackagewillbesavedin/usr/src/redhat/RPMS/.
TherearedifferentsubdirectoriescorrespondingtovariousCPUmodels/generations.Ifthecompilationdidnt
involvespecificfeaturesfromthesechipsthenthepackagewillbesavedinthenoarchdirectory.

Method2:
Thismethodtriggersthesamechainofeventsasthepreviousonebutisstartedwiththefollowingsingle
command:
rpmrebuildnameversionrelease.src.rpm

Method3:
Insomecasesdeveloperswilldistributeatarballtogetherwithaspecfile.Ifthetarballiscalledname
versionrelease.tar.gzyoucansearchfora.specfilewiththefollowing:
tartzvfnameversionrelease.tar.gz|grep.spec

IfthetarballhasaspecfilethenyoucanbuildanRPMpackagebytyping:
rpmbtnameversionrelease.tar.gz

5.DebianPackageManagement
SystemsusingDebianbasedvariantsofLinuxdon'tusetherpmpackagemanagementsystem,butrather
theDebianPackageManagementsystem.TheDebiansystemismorerigorousandconfigurablethanthe
rpmsystem,butforhistoricalreasonsislesswidelyused.
TheapproachusedbythetheDebiansystemisverysimilartothatusedbytherpmsystem.Theequivalent
commandto'rpm'inaDebiansystemis'dpkg'.
PackageNaming

________________________________________________________________________________________

Page125

LinuxITTechnicalTrainingCentre

SoftwareInstallation

_________________________________________________
SimilarlytoRPMbasedsystem,Debianpackagescomeinfileswhosenamesareformedasfollows:
name_versionrelease_architecture.deb
ThereleasenumberindicateswhichDebianreleaseoftheversionofthesoftwarethepackagecontains,
whilethearchitecturenamespecifiesthecomputerarchitecture(i386,sparc,all).
dpkg
dpkgisamediumleveltooltoinstall,build,removeandmanageDebianpackages.Otherfrontendpackages
aremorecommonlyusedtocontoldpkg,includingtheapttoolsandotherssuchasdselect.dpkgitselfis
controlledviacommandlineparameters,whichconsistofanactionandzeroormoreoptions.Theaction
parametertellsdpkgwhattodoandoptionscontrolthebehaviouroftheactioninsomeway.
dpkgmaintainssomeusableinformationaboutavailablepackages.Theinformationisdividedinthree
classes:states,selectionstatesandflags.
PackageStates
State

Description

installed

ThepackageisunpackedandconfiguredOK.

halfinstalled

Theinstallationofthepackagehasbeenstarted,butnotcompletedforsomereason.

notinstalled

Thepackageisnotinstalledonyoursystem.

unpacked

Thepackageisunpacked,butnotconfigured.

halfconfigured

Thepackageisunpackedandconfigurationhasbeenstarted,butnotyetcompletedfor
somereason.

configfiles

Onlytheconfigurationfilesofthepackageexistonthesystem.

PackageFlags
Flag

Description

hold

Apackagemarkedtobeonholdisnothandledbydpkg,unlessforcedtodothatwith
optionforcehold.

reinstrequired

Apackagemarkedreinstrequiredisbrokenandrequiresreinstallation.These
packagescannotberemoved,unlessforcedwithoptionforcereinstreq.

Actions
Theheartofdpkgoperationisthecommandlineparametersspecifyingtheactionwhichshouldbe
performed.Whiletherearealargenumberofthese,thefollowingtablesummarisesthemainactionsyouare
likelytorequireonanyregularbasis.
Action

Description

Printsalistofthepackagesinstalledonthesystem,ormatchingapatternifanyisgiven.

________________________________________________________________________________________

Page126

LinuxITTechnicalTrainingCentre

SoftwareInstallation

_________________________________________________
Thefirstthreecharactersoneachlineshowthestate,selectionstate,andflagsofthe
package
s

Showsthestatusandinformationaboutparticularinstalledpackage(s)

Showinformationaboutapackageina.debfile

Listthefilesincludedinapackage

Showthepackagewhichincludesthefilespecified

Install(orupgrade)andconfigureapackagefroma.debfile

unpack

Unpack(only)apackageina.debfile

configure

Configureanunpackedpackage.Witha(orpending)configuresallpackages
requiringconfiguration

Removeapackage(butleaveitsconfigurationfiles)

Purgeremoveapackagealongwithitsconfigurationfiles

getselections

Getalistofpackageselectionsfromasystem(tostdout)

setselections

Setthelistofpackageselectionsforasystem(fromstdin)

Options
Alloptionscanbespecifiedbothonthecommandlineandinthedpkgconfigurationfile/etc/dpkg/dpkg.cfg.
Eachlineintheconfigurationfileiseitheranoption(exactlythesameasthecommandlineoptionbutwithout
leadingdashes)oracomment(ifitstartswitha#).
Option

Description

forcething

Forcesdpkgtoperformanactionwhichitwouldnormallynottake(forexample,to
ignoredependencyinformationforcedepends,ortodowngradeapackagewith
forcedowngrade)

refusething

Refusetodosomethingwhichdpkgwouldnormallyautomaticallydo

ignoredepends Ignoredependencycheckingforapackage
noact

Showwhatdpkgwoulddo,butdon'tdoit(also:simulate)

Recursethroughdirectories(usingwithiorunpack)

Files
dpkgusesanumberoffilesinitsoperation,including/etc/dpkg/dpkg.cfgwhichcontainsdefault
configurationsettings.
Listsofavailablepackagesalongwiththeirstatusesareheldinthefiles
/var/lib/dpkg/availableand/var/lib/dpkg/status.
A.debfile,alongwiththefilesmakingupapackagesprograms,librariesandconfiguration,willalsoincludea
numberofcontrolfileswhichallowtheexecutionofscriptsbeforeandafterinstallationandremoval,along
________________________________________________________________________________________

Page127

LinuxITTechnicalTrainingCentre

SoftwareInstallation

_________________________________________________
withlistsoffilesandconfigurationfiles.Thesecanbefoundinthe/var/lib/dpkg/infodirectoryoncethe
packagesareinstalled.

Useofdpkg
Toinstallapackagefroma.debfile,youcouldusedpkgasfollows:

dpkgihello_2.1.14_i386.deb

OR

dpkgunpackhello_2.1.14_i386.deb
dpkgconfigurehello

Toremovethehellopackagealongwithitsconfiguration,youcoulduse:

dpkgPhello
While:

dpkgrhello
wouldremoveonlythepackage,leavingitsconfigurationfilesinstalled.
Thegetalistofallthepackagesinstalledonthesystem,usethecommand:

dpkgl
Notethatwhendealingwithapackagefile,thefilenameisgiven,whilewhendealingwithaninstalled
package,thepackagenameonlyisgiven.
APT
Thedpkgtoolisfineforinstallingindividualpackageswithnodependencies,butwheninstallinganumberof
packageswhichmayhavedependencies,theAPTtoolisgenerallyusedinstead.

APTisoneofthestrengthsofdpkg,andprovidesaneasywayofinstallingandupdatingasystem.Itis
controlledbytwofiles:
File

Description

/etc/apt/apt.conf

ContainsgeneralconfigurationoptionsforAPT,suchaswhichreleaseofDebianto
install,whether/whichproxysettingstouse,etc

________________________________________________________________________________________

Page128

LinuxITTechnicalTrainingCentre

SoftwareInstallation

_________________________________________________
/etc/apt/sources

ListssourcesofDebianfiles,whichmaybeonCDs,oronthenetwork

Ingeneral,touseAPTyoumustfirstconfigurethesourcesitistoused.Thiscanbedone(ifyouareusing
CDs)byusingthecommand:

aptsetup
whichaskstheusertochoosewhichmirrortodownloadfrom,andtestsit,orifyouareusingCDs,using:

aptcdrom
whichallowsindividualCDROMstobescannedforpackages.
OnceAPTknowswheretheDebianpackagesarelocated,twocommandlinetoolsareusedforpackage
management:aptcacheandaptget.
aptcache
aptcacheallowsmanipulationoftheAPTpackagecache(whichisstoredinfilesin/var/cache/apt).An
actionnormallyfollowsaptcacheonthecommandline,andcommonoptionsinclude:

Action

Description

search

Searchalltheavailablepackagedescriptionsforthestringgiven,andprintashort
descriptionofthematchingpackage

show

Showsafulldescriptionofthepackagespecified

aptget
Whileaptcacheisusefulforfindingoutinformationaboutavailablepackages,aptgetallowsupdatingof
packageinformation,retrieval,installationandremovalofpackages,andevenupgradingofanentireDebian
distribution.aptgetexpectsanactiontobeprovidedonthecommandline,andthemostcommonarelisted
below:
Action

Description

update

Updatethelistofpackagesfromthesourcesin/etc/apt/sources.list

installpackage

Installthepackage(s)specified,alongwithanydependencies

upgrade

Upgradeanypackageswhichhavenewerversionsavailable

distupgrade

Upgradeentiredistributiontothelatestrelease(besttoreadthereleasenotesfirst!)

remove

Removethepackage(s)specified

UseofAPT
________________________________________________________________________________________

Page129

LinuxITTechnicalTrainingCentre

SoftwareInstallation

_________________________________________________
ThetwomainusesofAPTareforupdatingthesystem(forexampleifsecurityrelatedupdateshavebecome
available).Thisisnormallydoneusingthetwocommands:

aptgetupdate

aptgetupgrade
TheothermainuseofAPTistoinstallrequiredpackages.Thisnormallyinvolvesthefollowingcommands:

aptgetupdate#updatelistofpackages

aptcachesearchfrob#findpackagesrelatingtofrobbing

aptcacheshowfrobnicate#showinformationregardingaparticular
package

aptgetinstallfrobnicate#installfrobnicatepackageandits
dependencies

6.TheAlienTool
ThealientoolwillchangeDebianpackagesintoRedHatonesandviceversa.Onecandownloaditat:
http://kitenet.net/programs/
Convertadebianpackagetoanrpm:

alien to-rpm

package.deb

Convertanrpmpackagetodebian:

alien to-debian package.rpm

________________________________________________________________________________________

Page130

LinuxITTechnicalTrainingCentre

SoftwareInstallation

_________________________________________________

7.ExercisesandSummary
ReviewQuestions(answersp.166)
YesorNo
1.Whenbuildingaprojectfromsourceonehastocompilesectionsofthecodeinthe
correctorderusinggcconthecommandline

_____

2.Theprogrammakewillonlybuildaprojectifitisstartedinadirectorycontaining
theappropriateMakefile

_____

3.PrecompiledbinarypackagesandsourcecodepackagesaretwotypesofRPM
packages

_____

4.Oncesharedlibrarieshavebeeninstalledfromsourceitisrecommendedtorunldconfig

_____

5.Theldconfigtoolisusedtoupdatetheldcache

_____

6.Programinstalledfromsourcecanbequeriedusingapackagemanager

_____

7.TheAPTtoolscaninstallpackagesandresolvealldependencies

_____

Glossary

Term

Description

build

termusedwhencompilingaprojectfromsource,usuallystartedbytypingmake

compile

translateprogramminginstructionswritteninahighlevellanguageintomachinereadable
code.Theoutputofacompilationiscalledtheobjectcode

dynamiclibrary

alibrarythatcanbeloadedatthesametimeastheexecutionofaprogram

sharedlibrary

alibraryintendedtobeusedbymorethanoneexecutable.Sharedlibrariesareoften
dynamiclibrariesandhavea.soextension(sharedobject)

staticlibrary

alibrarythatiscopiedintotheexecutableduringthecompilation.Staticlibrarieshave.a
extensions(archive)

highlevel
language

aprogramminglanguagereadablebyhumansusedtowritesourcecode

linker

1.programusedduringthecompilationprocesstoassembleobjectsgeneratedbythe
compilerintoanexecutableseeld(1)
2.programthatdynamicallyloadssharedlibrariesneededbyanexecutableatruntime
seeld.so(8)

objectcode

theoutputofacompilation.Objectcodeiseitheranexecutableormaybelinkedto
anotherobjectcodetoformanexecutable

________________________________________________________________________________________

Page131

LinuxITTechnicalTrainingCentre

SoftwareInstallation

_________________________________________________
sourcecode

programminginstructionswritteninahighlevellanguagethatneedtobecompiledwitha
compilerorinterpretedwithaninterpreter

tarball

acompressedtararchive

Files
File

Description

/etc/ld.so.conf

configurationfileforldconfig

Makefile

filereadbythemakeutilitywhenbuildingaproject

/etc/rpmrc

usedbyrpmandrpmbuild(seeLPI201),thisfilecontainsinformationsuchasthe
system'sarchitectureorthepathtomacrosandutilitiesusedwhenhandlingpackages.
Thisfileisoftenlocatedinthe/usr/lib/rpm/directory

/usr/lib/rpm/

directorycontainingallthemacrosneededwhenhandlingpackages

/var/lib/rpm/

directorywheredatabasesforthepackagemanager(RPM)arekept

Commands
Command

Description

alien

alien(1)Convertorinstallanalienbinarypackage.ItconvertsbetweenRedHatrpm,
Debiandeb,Stampedeslp,Slackwaretgz,andSolarispkgfileformats.Ifyouwanttousea
packagefromanotherLinuxdistributionthantheoneinstalledonyoursystemyoucanuse
alientoconvertittoyourpreferredpackageformatandinstallit

APTtools

ToolsusedtoperformadvancedoperationsonDebianpackageslocatedonaCDora
server

configure

scriptoftenincludedwithaprojectsourcecodeusedtocreatemakefiles.Itattemptsto
determineinformationsuchasthesystem'sCPUtypeorinstalledcomponentsneededto
buildtheproject(compiler,headerfilesorlibraries).

dpkg

toolusedtomanipulatepackagesintheDEBIANformat

LD_LIBRARY_ environmentvariablecontainingthesearchpathtosharedlibrariesusedbythelinker
PATH
(ld.so)
ldconfig

programthatbuildsthe'ldcache'usedbythelinkertofindsharedlibraries,withthepflagit
willprintthecurrentcontentofthecache

ldd

ldd(1)printsthesharedlibrariesrequiredbyeachprogramorsharedlibraryspecified
onthecommandline

make

infomakeThe`make'utilityautomaticallydetermineswhichpiecesofalargeprogram
needtoberecompiled,andissuescommandstorecompilethem.

rpm

toolusedtomanipulatepackagesintheRPMformat

________________________________________________________________________________________

Page132

LinuxITTechnicalTrainingCentre

SoftwareInstallation

_________________________________________________
Exercises
InthefollowingexamplesdownloadasourceRPMfile(e.g.bash2.058.src.rpmforRedHat7.2)from
www.rpmfind.net.
1.Installingasatarball.
ExtractthecontentsoftheRPMpackagewithoutcompilinganythingwith:
rpmivhbash2.058.src.rpm
Inthe/usr/src/redhat/SOURCESdirectory,unpackthetarballwith:
tarxvzfbash2.058.tar.gz

Optional(recommended!):Thepatchescanbeapplied.Dependingonwhichdirectoryyouarein
thesyntaxwillvary.
From/usr/src/redhat/SOURCES:
patchp0b<file.patch
From/usr/src/redhat/SOURCES/bash2.058
patchp1b<file.patch
Wewillchoosetoinstallthefilesinatemporaryrootdirectory,forexample/tmp/projecttest/.Ona
productionsystemtheusuallocationshouldbe /usr/local.Wecreatethisdirectory:
mkdir /tmp/project-test
Finallyfollowtheusualcompilationsteps.

./configureprefix=/tmp/projecttest
make
makeinstall
Youcannowlistthecontenton/tmp/projecttest.

2.(GoingfurthernotrequiredforLPI101)WenextrebuildtheprojectintoanRPMpackage.
rpmrebuildpackage.src.rpm
Thecompiledbinarypackageshouldbein/usr/src/redhat/RPMS
Checkthepackagescontentswiththeqploption
Installthepackage(s),andrunqueriesontheinstalledpackage
Uninstallthepackage
3.Configure/etc/apt/sourcesusingaptsetup.UsetheAPTtoolsanddpkgtoquery/install/updateavailable
packages.
________________________________________________________________________________________

Page133

LinuxITTechnicalTrainingCentre

AdvancedTextManipulation

______________________________________________

AdvancedTextManipulation
Prerequisites
TheCommandLine(p.64)
TextProcessing(p.102)

Goals
Distinguishexpressionsusedforfileglobbing(metacharacters)andregularexpressions
Usethegreptoolseffectively
Understandsimplesedcommands

Contents
ADVANCEDTEXTMANIPULATION.....................................................................................120
1.RegularExpressions.................................................................................................................. 121
2.Thegrepfamily.......................................................................................................................... 121
3.Workingwithgrep...................................................................................................................... 122
4.egrepandfgrep......................................................................................................................... 122
5.TheStreamEditorsed............................................................................................................. 123
6.ExercisesandSummary............................................................................................................ 125

_____________________________________________________________________________________

Page134

LinuxITTechnicalTrainingCentre

AdvancedTextManipulation

______________________________________________
Overview
Findingawordormultiplewordsinatextisachievedusinggrep,fgreporegrep.Thekeywordsused
duringasearchareacombinationofletterscalledregularexpressions.Regularexpressionsare
recognisedbymanyotherapplicationssuchassed,andvi.

1.RegularExpressions
TraditionalRegularExpressions(regex)
Aregularexpressionisasequenceofcharacters(oratoms)usedtomatchapattern.Charactersare
eitherconstants(treatedliterally)ormetacharacters.
Table1:Mainmetacharacters
Characters
\<KEY
WORD\>
^
$
[Range]
[^c]
\[
ca*t
.

SearchMatch
WordsbeginningwithKEY
WordsendingwithWORD
Beginningofaline
Endofaline
RangeofASCIIcharactersenclosed
Notthecharacterc
Interpretcharacter[literally
Stringscontainingcfollowedbyno'a'orany
numberoftheletter'a'followedbya't'
Matchanysinglecharacter

Extendedregex:Themaineregexsare:+,?,()and|
Table2:Listofmaineregex
Characters

SearchMatch

"A1|A2|A3"

StringscontainingA1orA2orA3

"ca+t"

Stringscontaininga'ca'followedbyanynumber
oftheletter'a'followedbya't'
Stringscontainingcfollowedbyno'a'orexactly
one'a'followedbya't'
Stringscontainingcfollowedbyno'a'orany
numberoftheletter'a'followedbya't'

"ca?t"
"ca*t"

2.Thegrepfamily
basicgrep
ThegreputilitysupportsregularexpressionsregexsuchasthoselistedinTable1.
_____________________________________________________________________________________

Page135

LinuxITTechnicalTrainingCentre

AdvancedTextManipulation

______________________________________________
egrep
TheegreptoolsupportsextendedregularexpressionseregexsuchasthoselistedinTable2.

fgrep
Fgrepstandsforfastgrepandfgrepinterpretsstringsliterally(noregexoreregexsupport)

3.Workingwithgrep
Syntaxforgrep:
grepPATTERNFILE

grep
c
f
i
n
v
w

MainOptions
countthenumberoflinesmatchingPATTERN
obtainPATTERNfromafile
ignorecasesensitivity
indicatetheinputfile'slinenumber
outputalllineexceptthosecontainingPATTERN
matchexactPATTERN

Forexamplelistallnonblanklinesin/etc/lilo.conf:

grepv^$/etc/lilo.conf

4.egrepandfgrep
Thefgreputilitydoesnotrecognisethespecialmeaningoftheregularexpressions.Forexample

fgrepcat*FILE

willonlymatchwordscontainingcat*.Themainimprovementcamefromfgrepsabilitytosearchfroma
listofkeywordsenteredlinebylineinafile,sayLIST.Thesyntaxwouldbe
fgrepfLISTFILE
_____________________________________________________________________________________

Page136

LinuxITTechnicalTrainingCentre

AdvancedTextManipulation

______________________________________________
Theegreputilitywillhandleanymodernregularexpressions.Itcanalsosearchforseveralkeywordsif
theyareenteredatthecommandline,separatedbypipes.Forexample;

egreplinux|^image/etc/lilo.conf

5.TheStreamEditorsed
Atthispointthestreameditormakesitsappearance!Itisanoldtypeoftoolandoriginallytheonlyone
availableunderUNIXtomanipulatetext.
Thesedutilityismostoftenusedtosearchandreplacepatternsintext.Itsupportsmostregular
expressions.

5.1Beginningsed
Syntaxforsed
sed[options]command[INPUTFILE]
Theinputfileisoptionalsincesedalsoworksonfileredirectionsandpipes.
HereareafewexamplesassumingweareworkingonafilecalledMODIF.

Deleteallcommentedlines:

sed/^#/dMODIF
Noticethatthesearchpatternisbetweenthedoubleslashs//.

Substitute/dev/hda1by/dev/sdb3:

seds/\/dev\/hda1/\/dev\/sdb3/gMODIF

Thesinthecommandstandsforsubstitute.Thegstandsforgloballyandforcesthesubstitutionto
takeplacethroughouteachline.
_____________________________________________________________________________________

Page137

LinuxITTechnicalTrainingCentre

AdvancedTextManipulation

______________________________________________
IfthelinecontainsthekeywordKEYthensubstitute:with;globally:

sed/KEY/s/:/;/gMODIF

5.2MoreAdvancedsed
Youcanissueseveralcommandseachstartingwitheatthecommandline.Forexample,(1)deleteall
blanksthen(2)substituteOLDbyNEWinthefileMODIF

sede/^$/des/OLD/NEW/gMODIF
Thesecommandscanalsobewrittentoafile,sayCOMMANDS.Theneachlineisinterpretedasanew
commandtoexecute(noquotesareneeded).
AnexampleCOMMANDSfile
1s/old/new/
/keyword/s/old/new/g
23,25d

ThesyntaxtousethisCOMMANDSfileis:
sedfCOMMANDSMODIF
Thisismuchmorecompactthanaverylongcommandline!
Summaryofoptionsforsed
Commandlineflags
eExecutethefollowingcommand
fReadcommandsfromafile
nDonotprintoutuneditedlines
sedcommands
dDeleteanentireline
rReadafileandappendtooutput
sSubstitute
wWriteoutputtoafile
_____________________________________________________________________________________

Page138

LinuxITTechnicalTrainingCentre

AdvancedTextManipulation

______________________________________________

6.ExercisesandSummary
ReviewQuestions(answersp.166)

YesorNo
1.Theextendedregularexpression'nucle?ar'willmatchnuclearandnuclar
____
2.Theregularexpression'baza*r'willmatchbazaarandbazarbutnotbazor

____

3.Theextendedregularexpression'nucle+ar'willonlymatchnuclear
____
4.Theregularexpression'baza*'willmatchbazaar,bazarandbazor
____
Commands
Command

Descriptionorapropos

egrep

printlinescontainingmatchingpatternsusingextendedregularexpressions

fgrep

printlinescontainingmatchingpatternsusingliteralstings

grep

printlinescontainingmatchingpatternsusingregularexpressions

sed

sed(1)streameditorisusedtoperformbasictexttransformationsonaninputstream
(afileorinputfromapipeline)

Exercises
1.CreateanewfilecalledFILEcontainingthelines:

Usinggrep,
fgrepand
egrep
togrepfor99%ofthecats
%thesearetwo
%commentedlines
Usegreptooutputonlyuncommentedlines.
Findalllinescontaininggrepexactly.(Notegrepnorfgrep.Usewtomatchtheword)
Findlinescontainingwordsstartingwithana

2.Regularexpressions.Appendthefollowinglinestothepreviousfile:
_____________________________________________________________________________________

Page139

LinuxITTechnicalTrainingCentre

AdvancedTextManipulation

______________________________________________
ct
cat
caats
caaatss
ca+t
ca*t
ca?t
crate
carts

Investigatetheoutcomeofthefollowingusinggrep,egrepandfgrep:
grep'ca+t'FILE
grep'ca?t'FILE
grep'ca.t'FILE
grep'caa*t'FILE
grep'ca*r.'FILE

3.UsesedtodothefollowingchangesinFILE
(useaCOMMANDfile,thendoeverythingonthecommandline)
inthefirstlinesubstitutegrep,withsoap

deletefgrepinthesecondline
substituteegrepwithwater
inthefourthlinereplacegrep forwith'wash'
Savetheresulttoafileusingthewoption

_____________________________________________________________________________________

Page140

LinuxITTechnicalTrainingCentre

Usingvi

______________________________________________

Usingvi
Prerequisites

none

Goals
Understandthethreeoperatingmodesofvi
Introducemostcommoneditingcommands
Recognisetheuseofregularexpressionsandsedlikecommands

Contents
USINGVI............................................................................................................................... 127
1.viModes.................................................................................................................................... 128
2.TextItems.................................................................................................................................. 128
3.InsertingText............................................................................................................................. 129
4.CutandPaste............................................................................................................................ 129
5.CopyPaste................................................................................................................................ 130
6.SearchandReplace................................................................................................................. 130
7.UndoandRedo.......................................................................................................................... 130
8.RunningaShellCommand........................................................................................................ 131
9.SaveandQuit............................................................................................................................ 131
10.ExercisesandSummary.......................................................................................................... 132

_____________________________________________________________________________________

Page141

LinuxITTechnicalTrainingCentre

Usingvi

______________________________________________
InmostLinuxdistributionsviisthetexteditorofchoice.Itisconsideredanessentialadmintoolsuchas
greporcatandisfoundthereforeinthe/bindirectory.

1.viModes
Inordertoperformcomplexoperationssuchascopy/pastevicanoperateindifferentmodes.
Commandmode
Thisistheeditingandnavigationmode.Commandsareoftenjustaletter.Forexampleusejtojumpto
thenextline.
Asaruleofthumbifyouwanttoperformanoperationseveraltimesyoucanprecedethecommandbya
number.Forexample10jwilljump10lines.
Insomesituationsthearrowkeysonthekeyboardarenotmappedproperly,itisstillpossibletonavigate
usingthecommandshjklwiththefollowingeffect:

LastLine(orcolumn)Mode
Youenterthismodefromthecommandmodebytypingacolon.Thecolumnwillappearatthebottom
leftcornerofthescreen.Inthismodeyoucanperformasimplesearchoperation,save,quitorruna
shellcommand.
InsertMode
Theeasiestwaytoenterthismodewhileincommandmodeistouseiora.Thismodeisthemost
intuitiveandismainlyusedtointeractivelyentertextintoadocument.
TheEsckeywillexittheinsertmodeandreturntocommandmode

2.TextItems
Itemssuchaswordsandparagraphsaredefinedincommandmodetoalloweditingcommandstobe
appliedtotextdocumentswithoutusingamouse.
Word,sentencesandparagraphs

eresp.b
Movetotheend/beginingofthecurrentword
Movetothebegining/endofthecurrentsentence
(resp.)
Movetothebegining/endofthecurrentparagraph
{resp.)
w
Similartoebutincludesthespaceaftertheword
_____________________________________________________________________________________

Page142

LinuxITTechnicalTrainingCentre

Usingvi

______________________________________________
BeginningandEnd
^
$
1G
G

Beginningofline
Endofline
Beginningoffile
Endoffile

Allthesetextitemscanbeusedtonavigatethroughthetextoneword(w)orparagraph(})atatime,go
tothebeginningofaline(^)theendofthefile(G)etc.Onecanalsousethesetextitemstoexecute
commandssuchasdeletingandcopying.

3.InsertingText
Whenincommandmodetypingiwillallowyoutoentertextinthedocumentinteractively.Aswithall
otherfeaturesinvitherearemanyotherwaysofdoingthis.Thetablebelowlistsallpossibleinserting
modes.

Insertcommands
a
Appendtextwithcursoronthelastletteroftheline
A
Appendtextwithcursorafterlastletterattheendoftheline
i
Inserttextatthecurrentposition
o
Inserttextonanewlinebelow
O
Inserttextonanewlineabove
s
Deletethecurrentletterandinsert
S
Deletecurrentlineandinsert
Averyusefuloptionwhenmodifyingadocumentistodeleteasectionoftextyouwishtoreplacejust
beforeenteringinsertmode.Thisisdonebythechangeccommand.Astheothercommandsinthis
sectioncwillputyouintoINSERTmodebutyoucanspecifywhichportionofthetextneedstobe
deletedbefore.Forexample:
c$
willdeleteallthetextfromthecurrentcursorpositiontotheendoftheline.
Anothercommandusedtoreplaceasinglecharacter(nothingelse!)isr.Firstchoosewhichcharacter
needstobereplacedandputthecursoronthischaracter.Nextpressrfollowedbyanewcharacter.The
newcharacterwillreplacetheoldone.ThiscommandwillleavetheeditorinCOMMANDandnot
INSERTmode!

4.CutandPaste
Ifyouwanttodeleteasinglecharacterwhileincommandmodeyouwouldusexandddwoulddelete
thecurrentline.Onecanthenpastethedeleteditemwiththecommandp.

_____________________________________________________________________________________

Page143

LinuxITTechnicalTrainingCentre

Usingvi

______________________________________________
Remark:Nearlyallvicommandscanberepeatedbyspecifyinganumberinfrontofthecommand.You
canalsoapplythecommandtoatextitem(suchasword.,sentence,paragraph...)byplacingtheentity
afterthecommand.

Examples:
Deleteaword:
dw

Deletetextfromheretotheendofthecurrentline
d$
Deletetextfromheretotheendofthecurrentparagraph
d}
Onecansimultaneouslydeleteanitemandswitchtoinsertmodewiththeccommand.Asusualyoucan
usethiscommandtogetherwithatextitemsuchaswor{.

5.CopyPaste
Thecopyactioninviisthecommandy(foryank,thelettercwasalreadytakenforchange),andthe
pasteactionisstillp.
Ifanentirelineisyankedthepastedtextwillbeinsertedonthenextlinebelowthecursor.
Thetextselectionismadewiththefamiliartextitemsw,l,},$etc...Thereareafewexceptionssuchas
thelastexample.

Examples:
Copythetextfromheretotheendofthecurrentline
y$
Copytheentirecurrentline
yy
Copy3lines
3yy
Thelatestdeleteditemisalwaysbufferedandcanbepastedwiththepcommand.Thisisequivalent
to
acutandpasteoperation.

6.SearchandReplace

_____________________________________________________________________________________

Page144

LinuxITTechnicalTrainingCentre

Usingvi

______________________________________________
Sincesearchinginvolvespatternmatchingwefindourselvesonceagaindealingwithregularexpressions
(regex).AsmanyUNIXtextmanipulationtoolssuchasgreporsed,virecognisesregularexpressions
too.
ToperformasearchonemustbeinCOMMANDmode.The/(forwardslash)commandsearches
forwardandthe?commandsearchesbackwards.
Onecanalsoperformsearchandreplaceoperations.Thesyntaxissimilartosed.
Example:
Downwardsearchforwordsbeginningwithcompinallthetext
/\<comp
Upwardsearchforlinesstartingwiththeletterz
?^z
SearchinthewholetextforthekeywordVARandreplaceitbyvar
:%s/VAR/var

7.UndoandRedo
Atthisstageisisworthmentioningthatonecanalwaysundochanges!ThismustbedoneinCOMMAND
modewiththeucommand(worksaslongasonehasntyetsavedthefile).Theredocommandis^R.

8.RunningaShellCommand
WhileinLASTLINEmodeeverythingfollowinganexclamationmark!isinterpretedasashellcommand.
Forexamplewhileeditinglilo.conforgrub.confyoumayneedtofindoutthenameoftherootdevice.
Thiscanbedonewith:
:!df/

9.SaveandQuit

Thecommandforsavingis:w.Bydefaultthecompletedocumentissaved.Insomecaseviwillrefuseto
savechangesmadetoadocumentbecauseofinsufficientrights.Insuchcasesionecanattempttoforce
awritewith:w!
Onecanalsospecifyanalternativenameforthefile.Portionsofthetextcanbesavedtoanotherfile
whileotherfilescanbereadandpastedinthecurrentdocument.Herearetheexampleswhichillustrate
this.
Examples:
Savethecurrentdocumentasnewfile
:wnewfile
_____________________________________________________________________________________

Page145

LinuxITTechnicalTrainingCentre

Usingvi

______________________________________________
Savelines15to24inafilecalledextract
:w15,24extract

Readfromfileextract.Thetextwillbepastedatthecursor
:rextract
Warning:Inthecolumnmodecontextwehavethefollowing
.
isthecurrentline
$
istheendofthedocument
Thefollowingaredifferentwaysavailabletoquitvi:

:wq
saveandquit
:q!
quitbutdonotsavechanges
:x
exitandsavewhenchangesexist
:quit
sameas:q
:exitor:e
sameas:x
ZZ
sameas:x

_____________________________________________________________________________________

Page146

LinuxITTechnicalTrainingCentre

Usingvi

______________________________________________

10.ExercisesandSummary
ReviewQuestions(answersp.166)
YesorNo
1.Thecommand'l'(lowercaseL)willplacethecursoronepositiontotheleft

_____

2.Thecommand3ddwilldeletethreelines

_____

3.Thecommand3wdwilldeletethreewords

_____

4.Thecommand:qwwillwriteandexit

_____

Commands
viaction

Description

^,$

beginningandendofline

1G,G

beginningandendofdocument

b,e

beginningandendofword

(,)

beginningandendofsentence

{,}

beginningandendofparagraph

w,W

wordandwordincludinghyphensandpunctuations

h,j,k,l

left,up,down,rightnavigationcommands

:!

callashellcommand

:quit,:q

quit

:quit!,:q!

forcequit,discardchanges

:wq

writeandquit

:exit,:x,:e,ZZ

exit(saveschangesifneeded)

/,?

searchforwardsorbackwards

a,A,i,o,O,s,S

startinsertmode

startinsertmodewhilechanginganitem

replaceasinglecharacterincommandmode

d,dd

deleteanitemordeleteentireline

deleteasinglecharacter

y,yy

yankitemorentireline

pastecontentofbuffer

u,^R

undo,redo

_____________________________________________________________________________________

Page147

LinuxITTechnicalTrainingCentre

Usingvi

______________________________________________

Exercises
Asrootcp/var/log/messagesto/tmp.Usingvissearchandreplaceutilitymakeeachlinebeginwith
printandendwith;
Typeutoundoallthechanges
Copy/etc/lilo.confto/tmp,editthisfileandtrytocopy/pasteyy/pandcut/pastewithdd/p
Investigatetheoutcomeof:x,ZZ,:quit,:wq,and:q!(whichonessaveandwhichonedon't?)
Investigatetheoutcomeforthevariousinsertingmodes:A,a,O,o,Sands
Optional:Ifyouhavetimethevimenhancedpackageinstallsaprogramcalledvimtutorwhichtakes
youthroughmostcommonvioptions.

_____________________________________________________________________________________

Page148

LinuxITTechnicalTrainingCentre

TheXEnvironment

______________________________________________

TheXEnvironment
Prerequisites

None

Goals
Understandthedifferentcomponentsofthe"Xwindows"environment
Recognisethefunctionofeachconfigurationfile(noeditingisexpected)
Runapplicationsonanydisplay
UnderstandthefunctionofadisplaymanagerincludingXDMCP

Contents

THEXENVIRONMENT.........................................................................................................134
1.Introduction................................................................................................................................ 135
2.ConfiguringX11R6.................................................................................................................... 136
3.ControllingXclients................................................................................................................... 138
4.StartingX................................................................................................................................... 139
5.TheDisplayManager................................................................................................................. 140
6.TroubleshootingXClients.......................................................................................................... 144
7.ChoosingaWindowManager.................................................................................................... 144
9.ExercisesandSummary............................................................................................................ 145

_____________________________________________________________________________________

Page149

LinuxITTechnicalTrainingCentre

TheXEnvironment

______________________________________________

1.Introduction
TheXWindowssystemwasdevelopedasthedisplaycomponentofProjectAthenaatthe
MassachusettsInstituteofTechnology.ItisthegraphicalenvironmentforUNIX.TheXWindowsystem
forLinuxisbasedonthefreelydistributableportofXWindowversion11release6(Commonlyreferred
toasX11R6).

Thisfreelydistributableportiscommonlyknownasxfree86forthe80386/80486andPentiumprocessor
families.Sinceitsinitialport,Xfree86hasbeenportedtoothercomputingplatforms,includingSystem
V/386and386BSD.

X11R6ComponentsandConfigurationSections

clientA

clientB

wm

monitor

xfs
X11R6

SectionFiles SectionMonitor

mouse

keyboard

video

SectionInputDeviceSectionInputDeviceSectionDevice
SectionPointer(old)Section"Keyboard"(old)

TheabovediagramshowsthecomponentsoftheX11R6server.TheSectionnamesreferto
configurationsectionsintheXF86Configconfigurationfile(coveredinthenextsection).

Thetwoclientsdepictedontopoftheserveraresocalledxapplications(e.gxclockorxterm).The
windowmanagerisalsoaclient.Windowmanagersaddwindowingfacilitiesaroundtheotherx
applicationclients,allowingfunctionalitiessuchaswindowdragging,focus,iconification,etc.

NOTICE:
TheX11R6serverisindependentfromtheclientsthatrunontop.Clientsareconfiguredusingspecific
_____________________________________________________________________________________

Page150

LinuxITTechnicalTrainingCentre

TheXEnvironment

______________________________________________
configurationfilesorglobalfilesusuallycalledXdefaultsorXresources.TheXserverconfiguration
filewillonlyconfigurecomponentssuchasthefontserverandfontdirectories,mouse,keyboard,
monitorresolutionandcolordepth.

2.ConfiguringX11R6
TwooftheconfigurationutilitiesprovidedwiththeXfree86softwarearetheXF86Setupandxf86config
scripts.Othervendorshavespecificutilitiessuchas:
Xconfigurator,redhatconfigxfree86(RedHat)
XFdrake(Mandrake)
sax(Suse)
Oncetheserverhasbeenconfiguredonecanchangethehorizontalandverticalsettingsforthemonitor
withxvidtune.

AlltheabovementionedconfigurationutilitieswillcreateandedittheXF86Configconfigurationfile.This
fileisreadatstartupbytheXServeranddeterminesitsbehaviour.Thisfileistypicallyfoundinthe
/etc/X11directory,andthisisitsfullpath:/etc/X11/XF86Config.
Thereare11configurationsectionsintheconfigfile,theyarelistedbelow:
ServerFlags
Module
InputDevice
Device
VideoAdapter
Monitor
Modes
Screen
ServerLayout
DRI
Vendor

NOTICE:
TheobsoletesectionnamesKeyboardandPointerarestillrecognisedforcompatabilityreasons,the
newsectionnameisnowInputDevice

OneofthefirstsectionsistheSectionFiles.TheFontPathkeywordtellswhethertogetfontsfroma
localdirectoryorfromafontserver.TheRgbPathkeywordisusedtoindicatethefullpathtorgbtextfile
usedtomapcolornamestoRGBnotation:
Section Files
FontPath /path/to/fonts/dir/
FontPath trans/hostname:port
RgbPath
"/path/to/rgb"
EndSection
_____________________________________________________________________________________

Page151

LinuxITTechnicalTrainingCentre

TheXEnvironment

______________________________________________
Wheretransisthetransporttypeunix,hostnameisthefullyqualifieddomainnameofthefontserver,
andportistheporttoconnectto,usuallyport7100.
Example:
FontPathunix/:7100
#LocalFontServer
FontPathunix/myfontserver.mydomain.com:7100

BelowisasampleXF86Config

file:
Section"Files"
RgbPath"/usr/X11R6/lib/X11/rgb"
FontPath
"/usr/X11R6/lib/X11/fonts/misc:unscaled,/usr/X11R6/lib/X11/fonts/75dpi:unsc
aled,/usr/X11R6/lib/X11/fonts/100dpi:unscaled,/usr/X11R6/lib/X11/fonts/misc
/"
EndSection

Section"InputDevice"
Identifier"Keyboard0"
Driver"keyboard"
EndSection
Section"InputDevice"
Identifier"Mouse0"
Driver"mouse"
Option"Protocol""IMPS/2"
Option"Device""/dev/psaux"
Option"ZAxisMapping""45"
EndSection
Section"Monitor"
Identifier"PrimaryMonitor"
VendorName"Unknown"
ModelName"Unknown"
HorizSync31.537.9
VertRefresh5590
Modeline"800x600"40.008008409681056600601605628+hsync
+vsync
EndSection
Section"Device"
Identifier"PrimaryCard"
VendorName"Unknown"
BoardName"None"
VideoRam2048
EndSection
Section"Screen"
Driver"Accel"
Device"PrimaryCard"
Monitor"PrimaryMonitor"
DefaultColorDepth24
BlankTime0
_____________________________________________________________________________________

Page152

LinuxITTechnicalTrainingCentre

TheXEnvironment

______________________________________________
SuspendTime0
OffTime0

SubSection"Display"
Depth24
Modes"800x600"
EndSubSection
SubSection"Display"
Depth32
Modes"800x600"

3.ControllingXclients
SettingFontsandColours
Xclientsareconfiguredusingthe.Xresourcesor.Xdefaultsfile.Thesefilearekeptintheusershome
directory.Itisnotautomaticallycreatedbydefault,assystemwidedefaultsarealsoavailableforeach
program.
Belowisanextractfroma.Xresources:
xterm_color*background: Black
xterm_color*foreground: Wheat
xterm_color*cursorColor: Orchid
xterm_color*reverseVideo: false
xterm_color*scrollBar: true
xterm_color*saveLines: 5000
xterm_color*reverseWrap: true
xterm_color*font: fixed
xterm_color.geometry: 80x25+20+20
xterm_color*fullCursor: true
xterm_color*scrollTtyOutput: off
xterm_color*scrollKey: on
term_color*VT100.Translations: #override\n\
<KeyPress>Prior : scroll-back(1,page)\n\
<KeyPress>Next : scroll-forw(1,page)
xterm_color*titleBar: false
Eachofthesedirectivesisasystemdefaultdirectivethatdescribeshowaclientwillbedisplayed.Each
lineconsistsoftheclientnamefollowedbyanasteriskandtheXWindowparameter.Throughacarefully
configured.Xresourcesfiletheusercandefinethewayaclientwilllookeachtimeitisstarted.
TheDISPLAYVariable
Whenanxapplication(orXclient)isstarteditneedstoknowwhichXservertorunon.AnXserveris
referredtoasadisplay.ForexamplethefirstXserveryoustart(usingstartxforexample)iscalled:0
thesecondwouldbecalled:1andsoon.ThefirstXserver(ordisplay)runningonthehost192.168.1.99
iscalled192.168.1.99:0

_____________________________________________________________________________________

Page153

LinuxITTechnicalTrainingCentre

TheXEnvironment

______________________________________________
MostnativeXclientssuchasxtermorxclockhavea-displayswitchwhichcanbeusedtosetthe
display.ButtheeasiestmethodistosettheenvironmentvariablecalledDISPLAY!
Thenexttwocommandsareequivalent:

xclock -display 192.168.1.99:0

DISPLAY=192.168.1.99:0 xclock

HowevertheXserveronthehost192.168.1.99willnotallowthisxapplicationtorun.Theuserthat
startedtheXserverontheremotehost(192.168.1.99)needstorunthexhostcommand.Thistoolcan
selectivelyaddorremovehoststoanaccesscontrollist.
Example:Allowremotexapplicationsfromhost192.168.1.7torunonlocalserver

xhost + 192.168.1.7
192.168.1.7 being added to access control list

NOTICE
Thexhostmechanismmustbeusedinconjunctionwithxauth(notpartoftheLPIobjectives).Fora
remotexclientfrom192.168.1.7torunonourlocalserverwestillneedtorunthefollowingonthelocal
host:

xauth extract - $DISPLAY | ssh 192.168.1.7

xauth merge -

(Assumingthattheusernamesarethesameandthatthehostnamecontainedin$DISPLAYcanbe
resolved)

4.StartingX
AnXsessioncanbestartedusing2methods:
Method1:Fromthecommandline,afterlogginginontoavirtualterminaltheuserlaunchestheXServer
usingascriptcalledstartx
Method2:ADisplayManagerisrunningpromptingtheuserwithagraphicallogin,thisisavailablefora
specificrunlevel(onRedHattypedistributionsthisisrunlevel5).
1.FromtheCommandLine

_____________________________________________________________________________________

Page154

LinuxITTechnicalTrainingCentre

TheXEnvironment

______________________________________________
Thestartxscriptstartsxinit.Thexinitscripthastwomainarguments(a)theXserverand(b)the
xinitrcscript.Thexinitrcscriptwillsource(read)thefilesXresourses(controllingthexapplications)
andtheXclients(choosingawindowmanager).Sowecantracethestartupsequenceasfollows:
startx>xinit>X>xinitrc>Xclients
2.UsingaDisplayManager
Adisplaymanagerwillautomaticallybestartedifthesystemisrunninginagivenrunlevel(e.grunlevel
5).Wefirstdescribetheloginprocess,thenextsectioncoversmoreadvancedfunctionalitiesofa
DisplayManager.Theloginprocessfollowsthefollowingsteps:.
xdm>xlogin>Xsession>(optionally)Xclientsor~/.Xclients
DifferentversionsofdisplaymanagersaswellasdifferentLinuxdistributionsmayuseslightlydifferent
steps.Ingeneralhowever,notethatstartxusesxinitwhereasxdmusesXsession.
CUSTOMISING
Eachusercanfurthercustomisetheirenvironmentbyusinga.xinitrcfile.Thisfilewillbemergedinto
thesystemxinitrc.
Theswitdesktoolallowsuserstodefineacustom.Xclientsfile

5.TheDisplayManager
Therearethreemaindisplaymanagers,xdm(generic),gdm(GNOME)andkdm(KDE).Accordingtothe
LPIobjectivestheconfigurationfilesareinthefollowingdirectories:
/etc/X11/xdm/
/etc/X11/gdm/
/etc/X11/kdm/(seeLPIobjectivesattheendofthismanualp.179)
However,mostoftentheconfigurationfilesforkdmarein/usr/share/config/kdm(alsoseebelow).
KDM
ThisdisplaymanagerisinstalledwiththeKDEdesktopenvironment.Itisbasedonthegenericxdm
displaymanagerandsharesmanycommonconfigurationfiles.Theseconfigurationfilesforarein
/usr/share/config/kdm.Thefilethatcontrolsmostfunctionalitiesiskdmrc.
Thepathtothekdmbinaryis/usr/bin/kdm
KDMConfigurationfiles:
kdmrcXaccess(sameasxdm)Xservers(sameasxdm)Xsession(sameasxdm)Xsetup
Xstartup

_____________________________________________________________________________________

Page155

LinuxITTechnicalTrainingCentre

TheXEnvironment

______________________________________________
GDM
ThisdisplaymanagerisdistributedwiththeGNOMEdesktopenvironment.Themainconfigurationfileis
gdm.conf
Thepathtothegdmbinaryis/usr/bin/gdm
GDMConfigurationFiles(/etc/X11/gdm):
Sessions/gdm.conf

XDM
ThexdmdisplaymanagerispartoftheXfree86application.Themainconfigurationfileisxdmconfig
Thepathtothexdmbinaryis/usr/bin/xdm
XDMConfigurationFiles:

XaccessXresourcesXsessionxdmconfigXservers_

Wewilllookatthexdmconfigurationfilesinmoredetaillaterinthissection.
DisplayManagersareusedmainlyinrunlevel5:
Setdefaultrunlevelin/etc/inittab
id:5:initdefault:
Displaymanagersallowlocaluserstologontothesystemusingthegraphicalinterface.Theycanalso
beusedtoprovideagraphicallogininterfaceoverthenetwork.Forthistheyuseaprotocolcalled
XDMCPorXDisplayManagerControlProtocol.BydefaultXDMCPisdisabled(wewillenableXDMCP
asanexercise).

XserverandDisplayManager

Welcome!!

DisplayManager
(xapplication)
xlogin
login
password
_____________________________________________________________________________________

Page156

LinuxITTechnicalTrainingCentre

TheXEnvironment

______________________________________________
XserverandDisplayManager

X11R6

ConfigurationFiles

/etc/X11/xdm/Xrescources
SincetheDisplayManagerisalsoanxapplication,thefonts,thebackgroundcolorsandxlogin
canbeconfiguredwiththeXresoursesfilein/etc/X11/xdm/.Whenusinggdm,the
/etc/X11/gdm/Init/DefaultscriptwillsourceXresources.

/etc/X11/xdm/Xservers
ThisfilesimplymapsthenameofadisplaywithanXserver.Forexampledisplay:0is
understood
tobethelocalXserver.RememberthatXalwaysrunsonthefirstfree/dev/tty.

/etc/X11/xdm/xdmconfig
Thisisthemainconfigurationfileforxdm.ItisalsousedtoenableXDMCP(seeexercises)

/etc/X11/xdm/Xaccess
ThisfileisusedtoenableXDMCP,allowingremotehoststodirectlyconnecttothelocalserver
(usingquery)orqueryaboutotherdisplay

TheXaccessfile
#$XConsortium:Xaccess,v1.591/08/2611:52:51rwsExp$
#
#AccesscontrolfileforXDMCPconnections
#TocontrolDirectandBroadcastaccess:
#
#
pattern
#
#TocontrolIndirectqueries:
#

_____________________________________________________________________________________

Page157

LinuxITTechnicalTrainingCentre

TheXEnvironment

______________________________________________
#
pattern
listofhostnamesand/ormacros...
#
#Tousethechooser:
#
#
pattern
CHOOSERBROADCAST
#
#or
#
#
pattern
CHOOSERlistofhostnamesand/ormacros...
#
#Todefinemacros:
#
#%name
listofhosts...
#
#Thefirstformtellsxdmwhichdisplaystorespondtoitself.
#Thesecondformtellsxdmtoforwardindirectqueriesfromhostsmatching
#thespecifiedpatterntotheindicatedlistofhosts.
#Thethirdformtellsxdmtohandleindirectqueriesusingthechooser;
#thechooserisdirectedtosenditsownqueriesoutviathebroadcast
#addressanddisplaytheresultsontheterminal.
#Thefourthformissimilartothethird,exceptinsteadofusingthe
#broadcastaddress,itsendsDirectQuerystoeachofthehostsinthelist
#
#Inallcases,xdmusesthefirstentrywhichmatchestheterminal;
#forIndirectQuerymessagesonlyentrieswithrighthandsidescan
#match,forDirectandBroadcastQuerymessages,onlyentrieswithout
#righthandsidescanmatch.
#
*

#anyhostcangetaloginwindow

#
#Tohardwireaspecificterminaltoaspecifichost,youcan
#leavetheterminalsendingindirectqueriestothishost,and
#useanentryoftheform:
#
#terminala

hosta

#Thenicestwaytorunthechooseristojustaskittobroadcast
#requeststothenetworkthatwaynewhostsshowupautomatically.
#Sometimes,however,thechoosercan'tfigureouthowtobroadcast,
#sothismaynotworkinallenvironments.
#
*

CHOOSERBROADCAST

#anyindirecthostcangetachooser

#Ifyou'dprefertoconfigurethesetofhostseachterminalsees,
#thenjustuncommenttheselines(andcommenttheCHOOSERlineabove)
#andeditthe%hostlistlineasappropriate
#
#%hostlist
hostahostb
#*
CHOOSER%hostlist
#

TheXserversfile
#$XConsortium:Xserv.ws.cpp,v1.393/09/2814:30:30gildeaExp$
#
#
#$XFree86:xc/programs/xdm/config/Xserv.ws.cpp,v1.1.1.1.12.21998/10/0415:23:14hohndelExp$
#
#Xserversfile,workstationprototype
#

_____________________________________________________________________________________

Page158

LinuxITTechnicalTrainingCentre

TheXEnvironment

______________________________________________
#Thisfileshouldcontainanentrytostarttheserveronthe
#localdisplay;ifyouhavemorethanonedisplay(notscreen),
#youcanaddentriestothelist(oneperline).Ifyoualso
#havesomeXterminalsconnectedwhichdonotsupportXDMCP,
#youcanaddthemhereaswell.EachXterminallineshould
#looklike:
#
XTerminalName:0foreign
#
:0local/usr/X11R6/bin/X

SincetheDisplayManagerisalsoanxapplicationtheXrescourcesfileissimilartothe.Xrescources
fileexceptthatitcontrolshowtheloginscreenisdisplayed.
SampleXrescourcesfile
! $XConsortium: Xresources /main/8 1996/11/11 09:24:46 swick $
xlogin*borderWidth: 3
xlogin*greeting: CLIENTHOST
xlogin*namePrompt: login:\040
xlogin*fail: Login incorrect
#ifdef COLOR
xlogin*greetColor: CadetBlue
xlogin*failColor: red
*Foreground: black
*Background: #fffff0
#else
xlogin*Foreground: black
xlogin*Background: white
#endif
XConsole.text.geometry:
XConsole.verbose:
true
XConsole*iconic:
true
XConsole*font:
fixed

480x130

Samplexdmconfigfile
!$XFree86:xc/programs/xdm/config/xdmconf.cpp,v1.1.1.2.4.21999/10/1218:33:29hohndelExp$
!
DisplayManager.servers:
/etc/X11/xdm/Xservers
DisplayManager.accessFile:
/etc/X11/xdm/Xaccess
!Alldisplaysshoulduseauthorization,butwecannotbesure
!Xterminalswillbeconfiguredthatway,sobydefault
!useauthorizationonlyforlocaldisplays:0,:1,etc.
DisplayManager._0.authorize: true
DisplayManager._1.authorize: true
!
DisplayManager*resources:
/etc/X11/xdm/Xresources
DisplayManager*session:
/etc/X11/xdm/Xsession
DisplayManager*authComplain: false
!SECURITY:donotlistenforXDMCPorChooserrequests
!CommentoutthislineifyouwanttomanageXterminalswithxdm
DisplayManager.requestPort:
0

6.TroubleshootingXClients
OccasionallyXClientswontterminateproperlyleavingzombieprocesses.Azombieprocessinone
whoseparentprocesseshasterminated,andcannotclearreferencestothechildprocess.Whenachild
processparentexitsleavingthechildprocessstillrunning,thisisusuallyvisiblebyrunningpswhichwill
_____________________________________________________________________________________

Page159

LinuxITTechnicalTrainingCentre

TheXEnvironment

______________________________________________
revealthechildprocessbeingownedbyPID1(init).Theseprocessesshouldbekilledbecausethey
maybeusingCPUresources.Killingsuchaprocessrequirestheusertobetheuserwhoownsthe
process,orroot.Itmightbenecessarytousethe9optiontoactuallykilltheseprocesses.

7.ChoosingaWindowManager
TheareathatiscommonlyreferredtoasthedesktopisalsoknownintheXWindowworldasthescreen.
Itcoverstheentireareaofyourmonitordisplay.Therootwindowisthebackgroundofyourscreen,
typicallyusedtodisplayacolourorpicture.Thewindowmanagerprovidesaninterfacebetweentheuser
andtheXserver.ItisvirtuallyimpossibletouseXwithoutawindowmanager,becauseitprovidesthe
titlebarandthefamiliarbuttonswithwhichyoumanipulatethedisplay.
InformationonavailablewindowmanagersisavailablefromtheWindowManagerswebsiteat
http://www.PliG.org/xwinman.ManyoftheLinuxversionsofthesewindowmanagersareavailableat
ftp://metalab.unc.edu
/pub/Linux/X11/windowmanagers.
Inadditiontothedifferentwindowmanagerstherearealsovariousdesktopenvironments,amongwhich
themostcommonareKDE,GNOMEandXFCE.
Belowisabrieflistofintegratedwindowmanagers:
Enlightenment
fvwm
icewm
amiWM
mlvwm
dfm
olwm
olvwm
mwm
WindowMaker

_____________________________________________________________________________________

Page160

LinuxITTechnicalTrainingCentre

TheXEnvironment

______________________________________________

9.ExercisesandSummary
ReviewQuestions(answersp.166)
YesorNo
1.TheconfigurationfileforawindowmanagerisXF86Config

____

2.AnxclientcanbeconfiguredtorunonanyXserveraccessibleonanetwork

____

3.Adisplaymanagerisaprogramthatmanagespixelswhenusinga
windowingenvironment

____

4.AuserrunninganXservercandisableaccesscontrolusingxhost

____

5.TheXDMCPprotocolisusedbydisplaymanagerstodisplayagraphicallogin
onremotecomputers

____

6.Ifasystemisnotrunningadisplaymanageroneusuallystartsawindowing
environmentwiththexinittool

____

Glossary
Term

Definition

DISPLAY

Shellenvironmentalvariableusedtonotifyxapplicationswhichdisplay(inthis
case,whichXserver)torunon

XDMCP

aprotocolthatprovidesauniformmechanismforanautonomous
displaytorequestloginservicefromaremotehost

runlevel

asoftwareconfigurationofthesystemwhichallowsonlyaselectedgroupof
processestoexistseeinit(8)

xclientorxapplication Inthismanualthetermsareusedtodescribeapplicationssuchasxtermor
xclockthatrunonanXserver
desktopenvironment

asuiteofapplications(includingawindowmanager)originallydesignedtouse
theentiresurfaceofthescreenasa'desktop'.Integratedapplicationsoften
includefeaturessuchasshortcutsforcopypasting,draganddrop,etc.
ExampledesktopsareXFCE,GNOMEandKDE

displaymanager

anxapplicationwhichrunsataspecificrunlevel(oftenrunlevel5)displaying
agraphicallogininterface.DisplaymanagersalsohandletheXDMCP
protocol.Mostcommondisplaymanagersarexdm(genericX11R6),gdm
(partoftheGNOMEdesktopsuite)andkdm(partoftheKDEdesktopsuite)

windowmanager

aspecialxapplicationwhichcanmove,resizeoriconifywindows.Insome
caseswindowmanagersalsoprovideataskbaraswellasdropdownmenus

_____________________________________________________________________________________

Page161

LinuxITTechnicalTrainingCentre

TheXEnvironment

______________________________________________
forquicklaunch.Examplesaretwm,fluxbox,icewmetc...
sessionmanager

providesawaytosaveawindowsessiononcetheuserlogsout

X11ConfigurationFile
File

Description

XF86Config

mainconfigurationfilefortheX11R6server

DisplayManagerConfigurationFiles
SystemFile

Description

gdm.conf

mainconfigurationfileforgdm

kdmrc

mainconfigurationfileforkdm

Xaccess

oneofthefilesusedtoallow/disallowXDMCPaccess

xdmconfig

mainconfigurationfileforxdm

Xrescources

customisationfileusedbydisplaymanagers

Xservers

configureshowmanydisplaymanagerstostartonasystem.Thefileassociatesa
display(default:0)toaserver(usuallyX11R6)

Xsession

scriptusedbydisplaymanagerstostartaspecificwindowingenvironment

Xclients

scriptusedbyXsessionaswellasxdmtostartasystemwidewindowingenvironment

UserCustomisations
File

Description

~/.Xresources
~/.Xdefaults

filesusedtocontrolthewayxapplicationsstart(e.gposition,fontsize,colours,etc)

~/.xinitrc

whenusingstartxuserscanspecifywhichwindowmanagerordesktopenvironment
tostart

~/.Xclients

whenusingadisplaymanageruserscanspecifywhichwindowmanagerordesktop
environmenttostart

Commands
_____________________________________________________________________________________

Page162

LinuxITTechnicalTrainingCentre

TheXEnvironment

______________________________________________
Command

Description

gdmp.156

gdm(1)GDMisareplacementforXDM,theXDisplayManager.Unlikeits
competitors(X3DM,KDM,WDM)GDMwaswrittenfromscratchanddoesnotcontain
anyoriginalXDM/XConsortiumcode.GDMrunsandmanagestheXserversforboth
localandremotelogins(usingXDMCP)

kdmp.155

adisplaymanagerprovidedbytheKDEdesktop,ithasmanyconfigurationfilesin
commonwithxdm

startxp.155 ascriptthatcallsxinitandstartstheXWindowSystem,thatisanXservertogetherwith
awindowmanageroradesktop
xauthp.154 (notanLPIobjective)xauth(1)Thexauthprogramisusedtoeditanddisplaythe
authorizationinformationusedinconnectingtotheXserver.Normallyxauthisnotused
tocreatetheauthorityfileentryinthefirstplace;xdmdoesthatseealsopam_xauth(8)
forfurtherreading
xdmp.156

theXDisplayManagermadeavailableaspartoftheXserver

xf86config
p.151

programthatinteractivelycreatesaXF86Configfile

XF86Setup graphicalprogramthatinteractivelycreatesormodifiesanXF86Configfile
p.151
xhostp.154 xhost(1)Thexhostprogramisusedtoaddanddeletehostnamesorusernamestothe
listallowedtomakeconnectionstotheXserver.Inthecaseofhosts,thisprovidesa
rudimentaryformofprivacycontrolandsecurity.Itisonlysufficientforaworkstation
(singleuser)environment,
xinitp.155

xinit(1)ThexinitprogramisusedtostarttheXWindowSystemserverandafirstclient
program(usuallyawindowmanager)onsystemsthatcannotstartXdirectlyfrom/etc/init
orinenvironmentsthatusemultiplewindowsystems.Whenthisfirstclientexits,xinitwill
killtheXserverandthenterminate

xinitrcp.155 scriptlaunchedbyxinitcontainingalistofclientstobestarted.Additionalclients(suchas
terminals,clocks,etc)shouldbestartedinthebackground.Thefirstclienthowever
(usuallythewindowmanager)shouldbestartedintheforgroundinordertoprevent
xinitrcfromexitingseexinit(1)
xvidtune
p.151

xvidtune(1)Withoutanyoptionsitpresentstheuserwithvariousbuttonsandsliders
thatcanbeusedtointeractivelyadjustexistingvideomodes.Itwillalsoprintthe
settingsinaformatsuitableforinclusioninanXF86Configfile

Exercises
Beforestartingmakesureyouarerunninginrunlevel3.
init 3
1.Logintoavirtualterminal(e.gAlt+F1)
2.Asrootsavetheexistingconfigurationfile/etc/X11/XF86Configandtryoutthevariousconfiguration
tools:
Redhat:Xconfigurator,redhatconfigxfree86(8.0)
Mandrake:XFdrake
_____________________________________________________________________________________

Page163

LinuxITTechnicalTrainingCentre

TheXEnvironment

______________________________________________
Suse:sax
XF86Setup
xf86config
X(thisistheX11serveritself,usetheconfigureflag)
3.StarttheXserverbytypingX.ThiswillstartX11R6alonewithnowindowmanagers.Returntoa
virtualterminal(e.gCtrl+Alt+F2)andgetthecommandlineback.Thendothefollowing:
exportDISPLAY=localhost:0
xterm&
GobackintoXbytypingCtrl+Alt+F7(ifyouhaventchangedthedefaultsin/etc/inittab...).Youshould
haveanxterminalrunning.Nexttypeinthisterminal:
twm&
Whathashappened?CanyoukilltwmwithoutkillingX?Gobacktoa
virtualterminal(e.gCtrl+Alt+F2)andtype:
X:1
Logintoanothervirtualterminal(e.gtty3)andtype:

exportDISPLAY=:1;xterm&
YounowhavetwoXserversrunningonscreen0and1.Howdoyouswitchfromonetoanother?
4.SettingupXDMCP
Forthistoworkmakesurethelinecontainingan*isuncommentedin/etc/X11/xdm/Xaccess.
Ifyouareusingxdmorkdmcommentoutthelineinxdmconfigasfollows
!DisplayManager.requestPort:0
Thislineisoriginallyuncommentedandallowsonlylocalloginrequestsonscreen0(moresecure).
Ifyouareusinggdmthenyouwillalsoneedtoeditgdm.confandput
enable=true
Thiswillturnoffthedefaultsecuritysettingsforgdm.
IfyourIPis1.2.3.4thenusersonyournetworkcanstartanXsessionwith:
Xquery1.2.3.4:1
or
Xindirect1.2.3.4:1

_____________________________________________________________________________________

Page164

LinuxITTechnicalTrainingCentre

AnswerstoReviewQuestions

______________________________________________

AnswerstoRevisionQuestions
Installation(p.9)
1.NotherawritetoolrunsunderDOS.Thetoolusedtocopyimagefilesontoablockdeviceisdd
2.Yesanydevicethatcanholddata(i.enotanextendedpartition)canbeusedastherootdevice
HardwareSuppport(p.28)
1.Notherootfilesystemcanbeonanydisktype
2.NothekernelmoduleonlyhandlestheUSBcontroller.ThekernelwillnotifyeventstoaUSBuser
agentwhichthenusesusermapstoconfiguretheparticulardevice
ManagingDevices(p.41)
1.Noyouneedtorerun/sbin/liloeverytimeyouchangesomethingin/etc/lilo.conf
2.YesGRUBonlyneedtobeinstalledonce
3.Nothe1024cylinderlimitaffectsthesecondstagebootloader
4.Yesonecannotsetquotasonadirectory
TheLinuxFilesystem(p.60)
1.Noprogramsstoredin/usr/arenotessentialforbootingupthesystem
2.Noauser'shomedirectorycanbeanywhereonthesystem
3.Yes
TheCommandLine(p.76)
1.Yes
2.NoSTDOUTcanberedirectedtoafile
3.Yes
4.Nocommandsaregenerallystoredinafilecalled.bash_historyintheuser'shomedirectory
FileManagement(p.88)
1.Yes
2.Nocdwithnoargumentwillalsogototheuser'shomedirectory
3.Noyoumustuse'mkdirp'tomakedirectorieswhichcontainsubdirectories
4.Yes
5.Nothecorrectcommandis'ln -s FILE FILE-LINK'
6.Nopathsbeginningwithaforwardslashareabsolutepaths
ProcessManagement(p.98)
1.Nokillwillsendasignal,somesignalsmaysimplypauseaprocess,othersforcedaemonstore
readtheirconfigurationfile.Howeverthedefaultsignal(15orSIGTERM)willattempttoterminatea
process.
2.Yes
3.Yes
4.No
TextProcessing(p.108)
1.Yes
2.Nousetail
3.Yesthisisthecasewithallthetexttools
4.NoallthetexttoolsprintthealtereddatatoSTDOUTanddon'taltertheoriginalfile
_____________________________________________________________________________________

Page165

LinuxITTechnicalTrainingCentre

AnswerstoReviewQuestions

______________________________________________
SoftwareInstallation(p.131)
1.Nooneusesmake
2.Yesamakefileisuniqueforeachproject.Themaketoolwillonlyreadamakefileinthecurrent
directory(i.ethedirectorythemakecommandisstartedfrom)
3.Yes
4.Yes
5.Yes
6.No
7.Yes
AdvancedTextManipulation(p.139)
1.Yesthe"e?"expressionreads'match0or1e'
2.Yesthe"a*"expressionreads'match0oranya'
3.Yesthe"e+"expressiomreads'matchatleast1oranye'
4.Yesnoticethatthe"a*"isattheendoftheexpression.Thismeansthat'baz'followedbyanything
willalsobematched
Usingvi(p.147)
1.Nolookatthepositionofhjklonthekeyboard.Thelkeyisontherightandwillcausethecursorto
movetotheright
2.Yes
3.No3wwillmovethecursorthreewordsforward,thendisanincompletecommand.Deletingthree
wordscanbedonewithd3w
4.Nothecommands:qwwillbereadfromlefttoright.Soquit(q)mustalwaysbelast
TheXEnvironment(p.161)
1.NotheXF86ConfigfileonlyconfigurestheXserver.Windowmanagersoftenusedirectoriesstored
inuser'shomedirectories
2.YesthisistruealthoughfirewallscanpreventxapplicationstoconnecttoremoteXservers
3.Noadisplaymanagerhandlesloginaccessonadisplay(localXserverorremoteXserverusing
XDMCP)
4.YesnotethatonmostoftherecentLinuxdistributionsxhostmustbeusedinconjunctionwithxauth
5.Yes
6.Nooneusuallyusesstartx

_____________________________________________________________________________________

Page166

LinuxITTechnicalTrainingCentre

LPI101Objectives
____________________________________________________________________

LPI101Objectives
http://www.lpi.org/en/obj_101.html
ThuNov404:45:582004

Exam101:DetailedObjectives
ThisisarequiredexamforLPIcertificationLevel1.Itcoversbasicsystemadministrationskillsthatarecommon
acrossalldistributionsofLinux.
Eachobjectiveisassignedaweightingvalue.Theweightsrangeroughlyfrom1to10,andindicatetherelative
importanceofeachobjective.Objectiveswithhigherweightswillbecoveredintheexamwithmorequestions.

Topic101:Hardware&Architecture
*1.101.1ConfigureFundamentalBIOSSettings
Modified:2003March17
Maintainer:KaraPritchard
Weight:1
Description:Candidatesshouldbeabletoconfigurefundamentalsystemhardwarebymakingthecorrect
settingsinthesystemBIOS.ThisobjectiveincludesaproperunderstandingofBIOSconfigurationissuessuchas
theuseofLBAonIDEharddiskslargerthan1024cylinders,enablingordisablingintegratedperipherals,aswellas
configuringsystemswith(orwithout)externalperipheralssuchaskeyboards.Italsoincludesthecorrectsettingfor
IRQ,DMAandI/OaddressesforallBIOSadministratedportsandsettingsforerrorhandling(p.13).
Keyfiles,terms,andutilitiesinclude:
/proc/ioports(p.13)
/proc/interrupts(p.13)
/proc/dma(p.13)
/proc/pci(p.13)
*1.101.3ConfigureModemandSoundcards
Modified:2003March17
Maintainer:KaraPritchard
Weight:1
Description:Ensuredevicesmeetcompatibilityrequirements(particularlythatthemodemisNOTawinmodem),
verifythatboththemodemandsoundcardareusinguniqueandcorrectIRQ's,I/O,andDMAaddresses,ifthe
soundcardisPnPinstallandrunsndconfig(p.26)andisapnp(p.15),configuremodemforoutbounddialup,
configuremodemforoutboundPPP|SLIP|CSLIPconnection,setserialportfor115.2Kbps(p.21)
*1.101.4SetupSCSIDevices
Modified:2003March17
Maintainer:KaraPritchard
Weight:1
______________________________________________________________________________________________

Page167

LinuxITTechnicalTrainingCentre

LPI101Objectives
____________________________________________________________________
Description:CandidatesshouldbeabletoconfigureSCSIdevicesusingtheSCSIBIOSaswellasthe
necessaryLinuxtools.TheyalsoshouldbeabletodifferentiatebetweenthevarioustypesofSCSI.Thisobjective
includesmanipulatingtheSCSIBIOStodetectusedandavailableSCSIIDsandsettingthecorrectIDnumberfor
differentdevicesespeciallythebootdevice.Italsoincludesmanagingthesettingsinthecomputer'sBIOSto
determinethedesiredbootsequenceifbothSCSIandIDEdrivesareused.

Keyfiles,terms,andutilitiesinclude:
SCSIID(p.17)
/proc/scsi/(p.17)
scsi_info(p.17)
*1.101.5SetupdifferentPCexpansioncards
Modified:2003March17
Maintainer:KaraPritchard
Weight:3
Description:Candidatesshouldbeabletoconfigurevariouscardsforthevariousexpansionslots.Theyshould
knowthedifferencesbetweenISAandPCIcardswithrespecttoconfigurationissues.Thisobjectiveincludesthe
correctsettingsofIRQs,DMAsandI/OPortsofthecards,especiallytoavoidconflictsbetweendevices.Italso
includesusingisapnpifthecardisanISAPnPdevice.
Keyfiles,terms,andutilitiesinclude:
/proc/dma
/proc/interrupts
/proc/ioports
/proc/pci
pnpdump(8)(p.15)
isapnp(8)(p.15)
lspci(8)(p.13)

*1.101.6ConfigureCommunicationDevices
Modified:2003March17
Maintainer:KaraPritchard
Weight:1
Description:Candidatesshouldbeabletoinstallandconfiguredifferentinternalandexternalcommunication
deviceslikemodems,ISDNadapters(p.23),andDSLswitches(p.23).Thisobjectiveincludesverificationof
compatibilityrequirements(especiallyimportantifthatmodemisawinmodem[p.22]),necessaryhardwaresettings
forinternaldevices(IRQs,DMAs,I/Oports),andloadingandconfiguringsuitabledevicedrivers.Italsoincludes
communicationdeviceandinterfaceconfigurationrequirements,suchastherightserialportfor115.2Kbps(p.21),
andthecorrectmodemsettingsforoutboundPPPconnection(s)(p.21).
Keyfiles,terms,andutilitiesinclude:
/proc/dma
/proc/interrupts
/proc/ioports
setserial(8)
______________________________________________________________________________________________

Page168

LinuxITTechnicalTrainingCentre

LPI101Objectives
____________________________________________________________________
*1.101.7ConfigureUSBdevices
Modified:2003March17
Maintainer:KaraPritchard
Weight:1
Description:CandidatesshouldbeabletoactivateUSBsupport,useandconfiguredifferentUSBdevices.This
objectiveincludesthecorrectselectionoftheUSBchipsetandthecorrespondingmodule.Italsoincludesthe
knowledgeofthebasicarchitectureofthelayermodelofUSBaswellasthedifferentmodulesusedinthedifferent
layers.

Keyfiles,terms,andutilitiesinclude:
lspci(8)
usbuhci.o(p.15)
usbohci.o(p.15)
/etc/usbmgr/(p.Error:Referencesourcenotfound16
usbmodules
/etc/hotplug(p.16)

Topic102:LinuxInstallation&PackageManagement

*1.102.1Designharddisklayout
Modified:2003March17
Maintainer:KaraPritchard
Weight:5
Description:CandidatesshouldbeabletodesignadiskpartitioningschemeforaLinuxsystem.Thisobjective
includesallocatingfilesystemsorswapspacetoseparatepartitionsordisks,andtailoringthedesigntotheintended
useofthesystem.Italsoincludesplacing/bootonapartitionthatconformswiththeBIOS'requirementsforbooting.
Keyfiles,terms,andutilitiesinclude:
/(root)filesystem(p.5andp.46)
/varfilesystem(p.48)
/homefilesystem(p.47)
swapspace(p.6)
mountpoints(p.5)
partitions(p.5,p.32)
cylinder1024(p.36andp.41)

*1.102.2Installabootmanager
Modified:2003March17
______________________________________________________________________________________________

Page169

LinuxITTechnicalTrainingCentre

LPI101Objectives
____________________________________________________________________
Maintainer:KaraPritchard
Weight:1
Description:Candidateshouldbeabletoselect,install,andconfigureabootmanager.Thisobjectiveincludes
providingalternativebootlocationsandbackupbootoptions(forexample,usingabootfloppy).
Keyfiles,terms,andutilitiesinclude:
/etc/lilo.conf(p.36)
/boot/grub/grub.conf(p.37)
lilo(p.36)
grubinstall(p.37)
MBR(p.36)
superblock(p.48)
firststagebootloader(p.36)

*1.102.3Makeandinstallprogramsfromsource
Modified:2003March17
Maintainer:KaraPritchard
Weight:5
Description:Candidatesshouldbeabletobuildandinstallanexecutableprogramfromsource.Thisobjective
includesbeingabletounpackafileofsources.Candidatesshouldbeabletomakesimplecustomizationstothe
Makefile,forexamplechangingpathsoraddingextraincludedirectories.
Keyfiles,terms,andutilitiesinclude:
gunzip
gzip(p.117)
bzip2(p.117)
tar(p.118)
configure(p.119)
make(p.119)

*1.102.4Managesharedlibraries
Modified:2003March17
Maintainer:KaraPritchard
Weight:3
Description:Candidatesshouldbeabletodeterminethesharedlibrariesthatexecutableprogramsdependon
andinstallthemwhennecessary.Candidatesshouldbeabletostatewheresystemlibrariesarekept.
______________________________________________________________________________________________

Page170

LinuxITTechnicalTrainingCentre

LPI101Objectives
____________________________________________________________________
Keyfiles,terms,andutilitiesinclude:
ldd(p.114)
ldconfig(p.115)
/etc/ld.so.conf(p.115)
LD_LIBRARY_PATH(p.115)

*1.102.5UseDebianpackagemanagement
Modified:2003March17
Maintainer:KaraPritchard
Weight:8
Description:CandidatesshouldbeabletoperformpackagemanagementskillsusingtheDebianpackage
manager.Thisobjectiveincludesbeingabletousecommandlineandinteractivetoolstoinstall,upgrade,or
uninstallpackages,aswellasfindpackagescontainingspecificfilesorsoftware(suchpackagesmightormightnot
beinstalled).Thisobjectivealsoincludesbeingabletoobtainpackageinformationlikeversion,content,
dependencies,packageintegrityandinstallationstatus(whetherornotthepackageisinstalled).
Keyfiles,terms,andutilitiesinclude:
unpack(p.127,p.127,p.128)
configure(p.127,p.128)
/etc/dpkg/dpkg.cfg(p.127)
/var/lib/dpkg/*(p.127)
/etc/apt/apt.conf(p.128)
/etc/apt/sources.list(p.129)
dpkg(p.125,.128)
dselect(p.126)
dpkgreconfigure
aptget(p.129)
alien(p.130,p.132)

*1.102.6UseRedHatPackageManager(RPM)
Modified:2003March17
Maintainer:KaraPritchard
Weight:8
Description:CandidatesshouldbeabletoperformpackagemanagementunderLinuxdistributionsthatuse
RPMsforpackagedistribution.Thisobjectiveincludesbeingabletoinstall,reinstall,upgrade,andremove
packages,aswellasobtainstatusandversioninformationonpackages.Thisobjectivealsoincludesobtaining
packageinformationsuchasversion,status,dependencies,integrity,andsignatures.Candidatesshouldbeableto
determinewhatfilesapackageprovides,aswellasfindwhichpackageaspecificfilecomesfrom.
Keyfiles,terms,andutilitiesinclude:
/etc/rpmrc(p.132)
/usr/lib/rpm/*(p.132)
rpm(p.120,p.132)
grep

______________________________________________________________________________________________

Page171

LinuxITTechnicalTrainingCentre

LPI101Objectives
____________________________________________________________________

Topic103:GNU&UnixCommands
*1.103.1Workonthecommandline
Modified:2003March17
Maintainer:KaraPritchard
Weight:5
Description:CandidatesshouldbeabletoInteractwithshellsandcommandsusingthecommandline.This
includestypingvalidcommandsandcommandsequences,defining,referencingandexportingenvironment
variables,usingcommandhistoryandeditingfacilities,invokingcommandsinthepathandoutsidethepath,using
commandsubstitution,applyingcommandsrecursivelythroughadirectorytreeandusingmantofindoutabout
commands.
Keyfiles,terms,andutilitiesinclude:
.
bash
echo(p.65)
env(p.66)
exec(p.73)
export(p.66)
man(p.75,p.74)
pwd(p.81)
set(p.66)
unset(p.66)
~/.bash_history(p.72)
~/.profile

*1.103.2Processtextstreamsusingfilters
Modified:2003March17
Maintainer:KaraPritchard
Weight:6

Description:Candidatesshouldshouldbeabletoapplyfilterstotextstreams.Tasksincludesendingtextfiles
andoutputstreamsthroughtextutilityfilterstomodifytheoutput,andusingstandardUNIXcommandsfoundinthe
GNUtextutilspackage.
Keyfiles,terms,andutilitiesinclude:
cat(p.102)
cut(p.106)
expand(p.104)
fmt(p.107)
head(p.103)
join(p.106)
nl(p.104)
______________________________________________________________________________________________

Page172

LinuxITTechnicalTrainingCentre

LPI101Objectives
____________________________________________________________________
od(p.104)
paste(p.106)
pr(p.107)
sed(p.137)
sort(p.107)
split(p.105)
tac(p.102)
tail(p.103)
tr(p.107)
unexpand(p.104)
uniq(p.105)
wc(p.103)

*1.103.3Performbasicfilemanagement
Modified:2003March17
Maintainer:KaraPritchard
Weight:3
Description:CandidatesshouldbeabletousethebasicUNIXcommandstocopy,move,andremovefilesand
directories.Tasksincludeadvancedfilemanagementoperationssuchascopyingmultiplefilesrecursively,removing
directoriesrecursively,andmovingfilesthatmeetawildcardpattern.Thisincludesusingsimpleandadvanced
wildcardspecificationstorefertofiles,aswellasusingfindtolocateandactonfilesbasedontype,size,ortime.
Keyfiles,terms,andutilitiesinclude:
cp(p.83)
find(p.81)
mkdir(p.83)
mv(p.84)
ls(p.83)
rm(p.83)
rmdir(p.83)
touch(p.85)
fileglobbing(p.76)

*1.103.4Usestreams,pipes,andredirects
Modified:2003March17
Maintainer:KaraPritchard
Weight:5
Description:Candidatesshouldbeabletoredirectstreamsandconnecttheminordertoefficientlyprocess
textualdata.Tasksincluderedirectingstandardinput,standardoutput,andstandarderror,pipingtheoutputofone
commandtotheinputofanothercommand,usingtheoutputofonecommandasargumentstoanothercommand
andsendingoutputtobothstdoutandafile.
Keyfiles,terms,andutilitiesinclude:
______________________________________________________________________________________________

Page173

LinuxITTechnicalTrainingCentre

LPI101Objectives
____________________________________________________________________
tee(p.70)
xargs(p.81)
<(p.69)
<<(p.73)
>(p.68)
>>(p.68)
|(p.70)
``(p.71)

*1.103.5Create,monitor,andkillprocesses
Modified:2003March17
Maintainer:KaraPritchard
Weight:5
Description:Candidatesshouldbeabletomanageprocesses.Thisincludesknowinghowtorunjobsinthe
foregroundandbackground,bringajobfromthebackgroundtotheforegroundandviceversa,startaprocessthat
willrunwithoutbeingconnectedtoaterminalandsignalaprogramtocontinuerunningafterlogout.Tasksalso
includemonitoringactiveprocesses,selectingandsortingprocessesfordisplay,sendingsignalstoprocesses,
killingprocessesandidentifyingandkillingXapplicationsthatdidnotterminateaftertheXsessionclosed.
Keyfiles,terms,andutilitiesinclude:
&(p.96)
bg(p.96)
fg(p.96)
jobs(p.96)
kill(p.93)
nohup(p.97)
ps(p.92)
top(p.93)

*1.103.6Modifyprocessexecutionpriorities
Modified:2003March17
Maintainer:KaraPritchard
Weight:3
Description:Candidatesshouldshouldbeabletomanageprocessexecutionpriorities.Tasksincluderunninga
programwithhigherorlowerpriority,determiningthepriorityofaprocessandchangingthepriorityofarunning
process.

Keyfiles,terms,andutilitiesinclude:
nice(p.94)
ps(p.92)
______________________________________________________________________________________________

Page174

LinuxITTechnicalTrainingCentre

LPI101Objectives
____________________________________________________________________
renice(p.95)
top(p.93)

*1.103.7Searchtextfilesusingregularexpressions
Modified:2003March17
Maintainer:KaraPritchard
Weight:3
Description:Candidatesshouldbeabletomanipulatefilesandtextdatausingregularexpressions.This
objectiveincludescreatingsimpleregularexpressionscontainingseveralnotationalelements.Italsoincludesusing
regularexpressiontoolstoperformsearchesthroughafilesystemorfilecontent.
Keyfiles,terms,andutilitiesinclude:
grep(p.135)
regexp()
sed(p.137)

*1.103.8Performbasicfileeditingoperationsusingvi
Modified:2003March17
Maintainer:KaraPritchard
Weight:1
Description:Candidatesshouldbeabletoedittextfilesusingvi.Thisobjectiveincludesvinavigation,basicvi
nodes,inserting,editing,deleting,copying,andfindingtext.
Keyfiles,terms,andutilitiesinclude:
vi(p.142)
/(p.145),?(p.Error:Referencesourcenotfound145)
h,j,k,l(p.142)
G,H,L
i(p.143),c(p143Error:Referencesourcenotfound),d,dd(p.143),p(p.Error:Referencesourcenotfound143),
o(p.Error:Referencesourcenotfound143),a(p.143)
ZZ(p.146),:w!(p.145),:q!(p.146),:e!(p.146)
:!(p.145)

Topic104:Devices,LinuxFilesystems,FilesystemHierarchyStandard
*1.104.1Createpartitionsandfilesystems
Modified:2003March17
Maintainer:KaraPritchard
Weight:3

______________________________________________________________________________________________

Page175

LinuxITTechnicalTrainingCentre

LPI101Objectives
____________________________________________________________________
Description:Candidatesshouldbeabletoconfigurediskpartitionsandthencreatefilesystemsonmediasuchas
harddisks.Thisobjectiveincludesusingvariousmkfscommandstosetuppartitionstovariousfilesystems,
includingext2,ext3,reiserfs,vfat,andxfs.
Keyfiles,terms,andutilitiesinclude:
fdisk(p.33)
mkfs(p.49)

*1.104.2Maintaintheintegrityoffilesystems
Modified:2003March17
Maintainer:KaraPritchard
Weight:3
Description:Candidatesshouldbeabletoverifytheintegrityoffilesystems,monitorfreespaceandinodes,and
repairsimplefilesystemproblems.Thisobjectiveincludesthecommandsrequiredtomaintainastandardfilesystem,
aswellastheextradataassociatedwithajournalingfilesystem.
Keyfiles,terms,andutilitiesinclude:
du(p.52)
df(p.51)
fsck(p.49)
e2fsck(p.49)
mke2fs(p.49)
debugfs(p.50)
dumpe2fs(p.50)
tune2fs(p.38)

*1.104.3Controlmountingandunmountingfilesystems
Modified:2003March17
Maintainer:KaraPritchard
Weight:3
Description:Candidatesshouldbeabletoconfigurethemountingofafilesystem.Thisobjectiveincludesthe
abilitytomanuallymountandunmountfilesystems,configurefilesystemmountingonbootup,andconfigureuser
mountableremoveablefilesystemssuchastapedrives,floppies,andCDs.
Keyfiles,terms,andutilitiesinclude:
/etc/fstab(p.37)
mount(p.38)
umount(p.39)

*1.104.4Managingdiskquota
Modified:2003March17
Maintainer:KaraPritchard
Weight:3
______________________________________________________________________________________________

Page176

LinuxITTechnicalTrainingCentre

LPI101Objectives
____________________________________________________________________
Description:Candidatesshouldbeabletomanagediskquotasforusers.Thisobjectiveincludessettingupa
diskquotaforafilesystem,editing,checking,andgeneratinguserquotareports.
Keyfiles,terms,andutilitiesinclude:
quota(p.40)
edquota(p.40)
repquota(p.40)
quotaon(p.40)

*1.104.5Usefilepermissionstocontrolaccesstofiles
Modified:2003March17
Maintainer:KaraPritchard
Weight:5
Description:Candidatesshouldbeabletocontrolfileaccessthroughpermissions.Thisobjectiveincludes
accesspermissionsonregularandspecialfilesaswellasdirectories.Alsoincludedareaccessmodessuchassuid,
sgid,andthestickybit,theuseofthegroupfieldtograntfileaccesstoworkgroups,theimmutableflag,andthe
defaultfilecreationmode.
Keyfiles,terms,andutilitiesinclude:
chmod(p.53)
umask(p.54)
chattr(p.57)

*1.104.6Managefileownership
Modified:2003March17
Maintainer:KaraPritchard
Weight:1
Description:Candidatesshouldbeabletocontroluserandgroupownershipoffiles.Thisobjectiveincludesthe
abilitytochangetheuserandgroupownerofafileaswellasthedefaultgroupownerfornewfiles.
Keyfiles,terms,andutilitiesinclude:
chmod(p.53)
chown(p.53)
chgrp(p.53)

*1.104.7Createandchangehardandsymboliclinks
Modified:2003March17
Maintainer:KaraPritchard
Weight:1
Description:Candidatesshouldbeabletocreateandmanagehardandsymboliclinkstoafile.Thisobjective
includestheabilitytocreateandidentifylinks,copyfilesthroughlinks,anduselinkedfilestosupportsystem
administrationtasks.
Keyfiles,terms,andutilitiesinclude:
ln(p.84)
______________________________________________________________________________________________

Page177

LinuxITTechnicalTrainingCentre

LPI101Objectives
____________________________________________________________________

*1.104.8Findsystemfilesandplacefilesinthecorrectlocation
Modified:2003March17
Maintainer:KaraPritchard
Weight:5
Description:CandidatesshouldbethouroughlyfamiliarwiththeFilesystemHierarchyStandard,includingtypical
filelocationsanddirectoryclassifications.ThisobjectiveincludestheabilitytofindfilesandcommandsonaLinux
system.
Keyfiles,terms,andutilitiesinclude:
find(p.81)
locate(p.82)
slocate(p.82)
updatedb(p.82)
whereis(p.82)
which(p.82)
/etc/updatedb.conf(p.82)

Topic110:TheXWindowSystem

*1.110.1Install&ConfigureXFree86
Modified:2003March17
Maintainer:KaraPritchard
Weight:5
Description:CandidateshouldbeabletoconfigureandinstallXandanXfontserver.Thisobjectiveincludes
verifyingthatthevideocardandmonitoraresupportedbyanXserver,aswellascustomizingandtuningXforthe
videocardandmonitor.ItalsoincludesinstallinganXfontserver,installingfonts,andconfiguringXtousethefont
server(mayrequireamanualeditof/etc/X11/XF86Configinthe"Files"section).
Keyfiles,terms,andutilitiesinclude:
XF86Setup(p.151)
xf86config(p.151)
xvidtune(p.151)
/etc/X11/XF86Config(p.Error:Referencesourcenotfound)
.Xresources(p.153)

*1.110.2Setupadisplaymanager
Modified:2003March17
Maintainer:KaraPritchard
Weight:3
______________________________________________________________________________________________

Page178

LinuxITTechnicalTrainingCentre

LPI101Objectives
____________________________________________________________________
Description:CandidateshouldbeablesetupandcustomizeaDisplaymanager.Thisobjectiveincludesturning
thedisplaymanageronoroffandchangingthedisplaymanagergreeting.Thisobjectiveincludeschangingdefault
bitplanesforthedisplaymanager.ItalsoincludesconfiguringdisplaymanagersforusebyXstations.Thisobjective
coversthedisplaymanagersXDM(XDisplayManger),GDM(GnomeDisplayManager)andKDM(KDEDisplay
Manager).
Keyfiles,terms,andutilitiesinclude:
/etc/inittab
/etc/X11/xdm/*(p.156)
/etc/X11/kdm/*(p.155)
/etc/X11/gdm/*(p.156)

*1.110.4Install&CustomizeaWindowManagerEnvironment
Modified:2003March17
Maintainer:KaraPritchard
Weight:5
Description:Candidateshouldbeabletocustomizeasystemwidedesktopenvironmentand/orwindow
manager,todemonstrateanunderstandingofcustomizationproceduresforwindowmanagermenusand/ordesktop
panelmenus.Thisobjectiveincludesselectingandconfiguringthedesiredxterminal(xterm,rxvt,atermetc.),
verifyingandresolvinglibrarydependencyissuesforXapplications,exportingXdisplaytoaclientworkstation.
Keyfiles,terms,andutilitiesinclude:
.xinitrc(p.155)
.Xdefaults(p.153)
xhost(p.154)
DISPLAYenvironmentvariable(p.154)

http://www.lpi.org/en/obj_101.html
Copyright1999,2000,2001,2002,2003LinuxProfessionalInstitute.Allrightsreserved.

______________________________________________________________________________________________

Page179

GNUFDLLicenseAgreement
________________________________________________________________________
Copyright (c) 2004 LinuxIT.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.2
or any later version published by the Free Software Foundation;
with the Invariant Sections being History, Acknowledgements, with the
Front-Cover Texts being released under the GFDL by LinuxIT.

GNUFreeDocumentationLicense
Version1.2,November2002
Copyright (C) 2000,2001,2002 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed
0.PREAMBLE
ThepurposeofthisLicenseistomakeamanual,textbook,orotherfunctionalandusefuldocument"free"in
thesenseoffreedom:toassureeveryonetheeffectivefreedomtocopyandredistributeit,withorwithout
modifyingit,eithercommerciallyornoncommercially.Secondarily,thisLicensepreservesfortheauthorand
publisherawaytogetcreditfortheirwork,whilenotbeingconsideredresponsibleformodificationsmadeby
others.
ThisLicenseisakindof"copyleft",whichmeansthatderivativeworksofthedocumentmustthemselvesbe
freeinthesamesense.ItcomplementstheGNUGeneralPublicLicense,whichisacopyleftlicense
designedforfreesoftware.
WehavedesignedthisLicenseinordertouseitformanualsforfreesoftware,becausefreesoftwareneeds
freedocumentation:afreeprogramshouldcomewithmanualsprovidingthesamefreedomsthatthe
softwaredoes.ButthisLicenseisnotlimitedtosoftwaremanuals;itcanbeusedforanytextualwork,
regardlessofsubjectmatterorwhetheritispublishedasaprintedbook.WerecommendthisLicense
principallyforworkswhosepurposeisinstructionorreference.
1.APPLICABILITYANDDEFINITIONS
ThisLicenseappliestoanymanualorotherwork,inanymedium,thatcontainsanoticeplacedbythe
copyrightholdersayingitcanbedistributedunderthetermsofthisLicense.Suchanoticegrantsaworld
wide,royaltyfreelicense,unlimitedinduration,tousethatworkundertheconditionsstatedherein.The
"Document",below,referstoanysuchmanualorwork.Anymemberofthepublicisalicensee,andis
addressedas"you".Youacceptthelicenseifyoucopy,modifyordistributetheworkinawayrequiring
permissionundercopyrightlaw.
A"ModifiedVersion"oftheDocumentmeansanyworkcontainingtheDocumentoraportionofit,either
copiedverbatim,orwithmodificationsand/ortranslatedintoanotherlanguage.
A"SecondarySection"isanamedappendixorafrontmattersectionoftheDocumentthatdealsexclusively
withtherelationshipofthepublishersorauthorsoftheDocumenttotheDocument'soverallsubject(orto
relatedmatters)andcontainsnothingthatcouldfalldirectlywithinthatoverallsubject.(Thus,iftheDocument
isinpartatextbookofmathematics,aSecondarySectionmaynotexplainanymathematics.)The
relationshipcouldbeamatterofhistoricalconnectionwiththesubjectorwithrelatedmatters,oroflegal,
commercial,philosophical,ethicalorpoliticalpositionregardingthem.
The"InvariantSections"arecertainSecondarySectionswhosetitlesaredesignated,asbeingthoseof
InvariantSections,inthenoticethatsaysthattheDocumentisreleasedunderthisLicense.Ifasectiondoes
notfittheabovedefinitionofSecondarythenitisnotallowedtobedesignatedasInvariant.TheDocument
____________________________________________________________________________________________________________

Page180

GNUFDLLicenseAgreement
________________________________________________________________________
maycontainzeroInvariantSections.IftheDocumentdoesnotidentifyanyInvariantSectionsthenthereare
none.
The"CoverTexts"arecertainshortpassagesoftextthatarelisted,asFrontCoverTextsorBackCover
Texts,inthenoticethatsaysthattheDocumentisreleasedunderthisLicense.AFrontCoverTextmaybeat
most5words,andaBackCoverTextmaybeatmost25words.
A"Transparent"copyoftheDocumentmeansamachinereadablecopy,representedinaformatwhose
specificationisavailabletothegeneralpublic,thatissuitableforrevisingthedocumentstraightforwardlywith
generictexteditorsor(forimagescomposedofpixels)genericpaintprogramsor(fordrawings)somewidely
availabledrawingeditor,andthatissuitableforinputtotextformattersorforautomatictranslationtoavariety
offormatssuitableforinputtotextformatters.AcopymadeinanotherwiseTransparentfileformatwhose
markup,orabsenceofmarkup,hasbeenarrangedtothwartordiscouragesubsequentmodificationby
readersisnotTransparent.AnimageformatisnotTransparentifusedforanysubstantialamountoftext.A
copythatisnot"Transparent"iscalled"Opaque".
ExamplesofsuitableformatsforTransparentcopiesincludeplainASCIIwithoutmarkup,Texinfoinput
format,LaTeXinputformat,SGMLorXMLusingapubliclyavailableDTD,andstandardconformingsimple
HTML,PostScriptorPDFdesignedforhumanmodification.Examplesoftransparentimageformatsinclude
PNG,XCFandJPG.Opaqueformatsincludeproprietaryformatsthatcanbereadandeditedonlyby
proprietarywordprocessors,SGMLorXMLforwhichtheDTDand/orprocessingtoolsarenotgenerally
available,andthemachinegeneratedHTML,PostScriptorPDFproducedbysomewordprocessorsfor
outputpurposesonly.
The"TitlePage"means,foraprintedbook,thetitlepageitself,plussuchfollowingpagesasareneededto
hold,legibly,thematerialthisLicenserequirestoappearinthetitlepage.Forworksinformatswhichdonot
haveanytitlepageassuch,"TitlePage"meansthetextnearthemostprominentappearanceofthework's
title,precedingthebeginningofthebodyofthetext.
Asection"EntitledXYZ"meansanamedsubunitoftheDocumentwhosetitleeitherispreciselyXYZor
containsXYZinparenthesesfollowingtextthattranslatesXYZinanotherlanguage.(HereXYZstandsfora
specificsectionnamementionedbelow,suchas"Acknowledgements","Dedications","Endorsements",or
"History".)To"PreservetheTitle"ofsuchasectionwhenyoumodifytheDocumentmeansthatitremainsa
section"EntitledXYZ"accordingtothisdefinition.
TheDocumentmayincludeWarrantyDisclaimersnexttothenoticewhichstatesthatthisLicenseappliesto
theDocument.TheseWarrantyDisclaimersareconsideredtobeincludedbyreferenceinthisLicense,but
onlyasregardsdisclaimingwarranties:anyotherimplicationthattheseWarrantyDisclaimersmayhaveis
voidandhasnoeffectonthemeaningofthisLicense.
2.VERBATIMCOPYING
YoumaycopyanddistributetheDocumentinanymedium,eithercommerciallyornoncommercially,provided
thatthisLicense,thecopyrightnotices,andthelicensenoticesayingthisLicenseappliestotheDocument
arereproducedinallcopies,andthatyouaddnootherconditionswhatsoevertothoseofthisLicense.You
maynotusetechnicalmeasurestoobstructorcontrolthereadingorfurthercopyingofthecopiesyoumake
ordistribute.However,youmayacceptcompensationinexchangeforcopies.Ifyoudistributealargeenough
numberofcopiesyoumustalsofollowtheconditionsinsection3.
Youmayalsolendcopies,underthesameconditionsstatedabove,andyoumaypubliclydisplaycopies.
3.COPYINGINQUANTITY
Ifyoupublishprintedcopies(orcopiesinmediathatcommonlyhaveprintedcovers)oftheDocument,
numberingmorethan100,andtheDocument'slicensenoticerequiresCoverTexts,youmustenclosethe
copiesincoversthatcarry,clearlyandlegibly,alltheseCoverTexts:FrontCoverTextsonthefrontcover,
andBackCoverTextsonthebackcover.Bothcoversmustalsoclearlyandlegiblyidentifyyouasthe
publisherofthesecopies.Thefrontcovermustpresentthefulltitlewithallwordsofthetitleequally
prominentandvisible.Youmayaddothermaterialonthecoversinaddition.Copyingwithchangeslimitedto
____________________________________________________________________________________________________________

Page181

GNUFDLLicenseAgreement
________________________________________________________________________
thecovers,aslongastheypreservethetitleoftheDocumentandsatisfytheseconditions,canbetreatedas
verbatimcopyinginotherrespects.
Iftherequiredtextsforeithercoveraretoovoluminoustofitlegibly,youshouldputthefirstoneslisted(as
manyasfitreasonably)ontheactualcover,andcontinuetherestontoadjacentpages.
IfyoupublishordistributeOpaquecopiesoftheDocumentnumberingmorethan100,youmusteither
includeamachinereadableTransparentcopyalongwitheachOpaquecopy,orstateinorwitheachOpaque
copyacomputernetworklocationfromwhichthegeneralnetworkusingpublichasaccesstodownloadusing
publicstandardnetworkprotocolsacompleteTransparentcopyoftheDocument,freeofaddedmaterial.If
youusethelatteroption,youmusttakereasonablyprudentsteps,whenyoubegindistributionofOpaque
copiesinquantity,toensurethatthisTransparentcopywillremainthusaccessibleatthestatedlocationuntil
atleastoneyearafterthelasttimeyoudistributeanOpaquecopy(directlyorthroughyouragentsor
retailers)ofthateditiontothepublic.
Itisrequested,butnotrequired,thatyoucontacttheauthorsoftheDocumentwellbeforeredistributingany
largenumberofcopies,togivethemachancetoprovideyouwithanupdatedversionoftheDocument.
4.MODIFICATIONS
YoumaycopyanddistributeaModifiedVersionoftheDocumentundertheconditionsofsections2and3
above,providedthatyoureleasetheModifiedVersionunderpreciselythisLicense,withtheModifiedVersion
fillingtheroleoftheDocument,thuslicensingdistributionandmodificationoftheModifiedVersiontowhoever
possessesacopyofit.Inaddition,youmustdothesethingsintheModifiedVersion:

A.UseintheTitlePage(andonthecovers,ifany)atitledistinctfromthatoftheDocument,andfrom
thoseofpreviousversions(whichshould,iftherewereany,belistedintheHistorysectionofthe
Document).Youmayusethesametitleasapreviousversioniftheoriginalpublisherofthatversion
givespermission.
B.ListontheTitlePage,asauthors,oneormorepersonsorentitiesresponsibleforauthorshipofthe
modificationsintheModifiedVersion,togetherwithatleastfiveoftheprincipalauthorsofthe
Document(allofitsprincipalauthors,ifithasfewerthanfive),unlesstheyreleaseyoufromthis
requirement.
C.StateontheTitlepagethenameofthepublisheroftheModifiedVersion,asthepublisher.
D.PreserveallthecopyrightnoticesoftheDocument.
E.Addanappropriatecopyrightnoticeforyourmodificationsadjacenttotheothercopyrightnotices.
F.Include,immediatelyafterthecopyrightnotices,alicensenoticegivingthepublicpermissionto
usetheModifiedVersionunderthetermsofthisLicense,intheformshownintheAddendumbelow.
G.PreserveinthatlicensenoticethefulllistsofInvariantSectionsandrequiredCoverTextsgivenin
theDocument'slicensenotice.
H.IncludeanunalteredcopyofthisLicense.
I.PreservethesectionEntitled"History",PreserveitsTitle,andaddtoitanitemstatingatleastthe
title,year,newauthors,andpublisheroftheModifiedVersionasgivenontheTitlePage.Ifthereis
nosectionEntitled"History"intheDocument,createonestatingthetitle,year,authors,andpublisher
oftheDocumentasgivenonitsTitlePage,thenaddanitemdescribingtheModifiedVersionas
statedintheprevioussentence.
J.Preservethenetworklocation,ifany,givenintheDocumentforpublicaccesstoaTransparent
copyoftheDocument,andlikewisethenetworklocationsgivenintheDocumentforprevious
versionsitwasbasedon.Thesemaybeplacedinthe"History"section.Youmayomitanetwork
locationforaworkthatwaspublishedatleastfouryearsbeforetheDocumentitself,oriftheoriginal
publisheroftheversionitreferstogivespermission.
K.ForanysectionEntitled"Acknowledgements"or"Dedications",PreservetheTitleofthesection,
andpreserveinthesectionallthesubstanceandtoneofeachofthecontributoracknowledgements
and/ordedicationsgiventherein.
L.PreservealltheInvariantSectionsoftheDocument,unalteredintheirtextandintheirtitles.
Sectionnumbersortheequivalentarenotconsideredpartofthesectiontitles.

____________________________________________________________________________________________________________

Page182

GNUFDLLicenseAgreement
________________________________________________________________________
M.DeleteanysectionEntitled"Endorsements".SuchasectionmaynotbeincludedintheModified
Version.
N.DonotretitleanyexistingsectiontobeEntitled"Endorsements"ortoconflictintitlewithany
InvariantSection.
O.PreserveanyWarrantyDisclaimers.
IftheModifiedVersionincludesnewfrontmattersectionsorappendicesthatqualifyasSecondarySections
andcontainnomaterialcopiedfromtheDocument,youmayatyouroptiondesignatesomeorallofthese
sectionsasinvariant.Todothis,addtheirtitlestothelistofInvariantSectionsintheModifiedVersion's
licensenotice.Thesetitlesmustbedistinctfromanyothersectiontitles.
YoumayaddasectionEntitled"Endorsements",provideditcontainsnothingbutendorsementsofyour
ModifiedVersionbyvariouspartiesforexample,statementsofpeerrevieworthatthetexthasbeen
approvedbyanorganizationastheauthoritativedefinitionofastandard.
YoumayaddapassageofuptofivewordsasaFrontCoverText,andapassageofupto25wordsasa
BackCoverText,totheendofthelistofCoverTextsintheModifiedVersion.OnlyonepassageofFront
CoverTextandoneofBackCoverTextmaybeaddedby(orthrougharrangementsmadeby)anyone
entity.IftheDocumentalreadyincludesacovertextforthesamecover,previouslyaddedbyyouorby
arrangementmadebythesameentityyouareactingonbehalfof,youmaynotaddanother;butyoumay
replacetheoldone,onexplicitpermissionfromthepreviouspublisherthataddedtheoldone.
Theauthor(s)andpublisher(s)oftheDocumentdonotbythisLicensegivepermissiontousetheirnamesfor
publicityforortoassertorimplyendorsementofanyModifiedVersion.
5.COMBININGDOCUMENTS
YoumaycombinetheDocumentwithotherdocumentsreleasedunderthisLicense,underthetermsdefined
insection4aboveformodifiedversions,providedthatyouincludeinthecombinationalloftheInvariant
Sectionsofalloftheoriginaldocuments,unmodified,andlistthemallasInvariantSectionsofyourcombined
workinitslicensenotice,andthatyoupreservealltheirWarrantyDisclaimers.
ThecombinedworkneedonlycontainonecopyofthisLicense,andmultipleidenticalInvariantSectionsmay
bereplacedwithasinglecopy.IftherearemultipleInvariantSectionswiththesamenamebutdifferent
contents,makethetitleofeachsuchsectionuniquebyaddingattheendofit,inparentheses,thenameof
theoriginalauthororpublisherofthatsectionifknown,orelseauniquenumber.Makethesameadjustment
tothesectiontitlesinthelistofInvariantSectionsinthelicensenoticeofthecombinedwork.
Inthecombination,youmustcombineanysectionsEntitled"History"inthevariousoriginaldocuments,
formingonesectionEntitled"History";likewisecombineanysectionsEntitled"Acknowledgements",andany
sectionsEntitled"Dedications".YoumustdeleteallsectionsEntitled"Endorsements."
6.COLLECTIONSOFDOCUMENTS
YoumaymakeacollectionconsistingoftheDocumentandotherdocumentsreleasedunderthisLicense,
andreplacetheindividualcopiesofthisLicenseinthevariousdocumentswithasinglecopythatisincluded
inthecollection,providedthatyoufollowtherulesofthisLicenseforverbatimcopyingofeachofthe
documentsinallotherrespects.
Youmayextractasingledocumentfromsuchacollection,anddistributeitindividuallyunderthisLicense,
providedyouinsertacopyofthisLicenseintotheextracteddocument,andfollowthisLicenseinallother
respectsregardingverbatimcopyingofthatdocument.
7.AGGREGATIONWITHINDEPENDENTWORKS
AcompilationoftheDocumentoritsderivativeswithotherseparateandindependentdocumentsorworks,in
oronavolumeofastorageordistributionmedium,iscalledan"aggregate"ifthecopyrightresultingfromthe
compilationisnotusedtolimitthelegalrightsofthecompilation'susersbeyondwhattheindividualworks
permit.WhentheDocumentisincludedinanaggregate,thisLicensedoesnotapplytotheotherworksinthe
aggregatewhicharenotthemselvesderivativeworksoftheDocument.
____________________________________________________________________________________________________________

Page183

GNUFDLLicenseAgreement
________________________________________________________________________
IftheCoverTextrequirementofsection3isapplicabletothesecopiesoftheDocument,thenifthe
Documentislessthanonehalfoftheentireaggregate,theDocument'sCoverTextsmaybeplacedon
coversthatbrackettheDocumentwithintheaggregate,ortheelectronicequivalentofcoversiftheDocument
isinelectronicform.Otherwisetheymustappearonprintedcoversthatbracketthewholeaggregate.
8.TRANSLATION
Translationisconsideredakindofmodification,soyoumaydistributetranslationsoftheDocumentunderthe
termsofsection4.ReplacingInvariantSectionswithtranslationsrequiresspecialpermissionfromtheir
copyrightholders,butyoumayincludetranslationsofsomeorallInvariantSectionsinadditiontotheoriginal
versionsoftheseInvariantSections.YoumayincludeatranslationofthisLicense,andallthelicensenotices
intheDocument,andanyWarrantyDisclaimers,providedthatyoualsoincludetheoriginalEnglishversionof
thisLicenseandtheoriginalversionsofthosenoticesanddisclaimers.Incaseofadisagreementbetween
thetranslationandtheoriginalversionofthisLicenseoranoticeordisclaimer,theoriginalversionwill
prevail.
IfasectionintheDocumentisEntitled"Acknowledgements","Dedications",or"History",therequirement
(section4)toPreserveitsTitle(section1)willtypicallyrequirechangingtheactualtitle.
9.TERMINATION
Youmaynotcopy,modify,sublicense,ordistributetheDocumentexceptasexpresslyprovidedforunderthis
License.Anyotherattempttocopy,modify,sublicenseordistributetheDocumentisvoid,andwill
automaticallyterminateyourrightsunderthisLicense.However,partieswhohavereceivedcopies,orrights,
fromyouunderthisLicensewillnothavetheirlicensesterminatedsolongassuchpartiesremaininfull
compliance.
10.FUTUREREVISIONSOFTHISLICENSE
TheFreeSoftwareFoundationmaypublishnew,revisedversionsoftheGNUFreeDocumentationLicense
fromtimetotime.Suchnewversionswillbesimilarinspirittothepresentversion,butmaydifferindetailto
addressnewproblemsorconcerns.Seehttp://www.gnu.org/copyleft/.
EachversionoftheLicenseisgivenadistinguishingversionnumber.IftheDocumentspecifiesthata
particularnumberedversionofthisLicense"oranylaterversion"appliestoit,youhavetheoptionoffollowing
thetermsandconditionseitherofthatspecifiedversionorofanylaterversionthathasbeenpublished(not
asadraft)bytheFreeSoftwareFoundation.IftheDocumentdoesnotspecifyaversionnumberofthis
License,youmaychooseanyversioneverpublished(notasadraft)bytheFreeSoftwareFoundation.

____________________________________________________________________________________________________________

Page184

LinuxITTechnicalTrainingCentre

Index

______________________________________________________

INDEX
A
ADSL 20
alias 64
append50
atime 50
B
bg
85
bootloaders
1024cylinderlimit
36
1024cylinders32
bootloader
31
GRUB 32
grubshell
32
grubinstall
32
grub.conf
32
LILO 31
/boot/boot.b 31
/etc/lilo.conf 32
/sbin/lilo
32
C
cat
90
cd
72
chattr 49
chgrp 46
chmod 46
chown 46
chroot 4
compoundcommands
command1&&command2
command1||command2
command1;command2
compress
50
configure
106p.
cp
74
CtrlZ 85
cut
93
D
dd
2,76
Debian 112
debugfs
43
df
45
dirsync50
DISPLAY
138
displaymanager
139
displaymanagers
gdm.conf
140
kdmrc 140
Xaccess
141

64
64
64

xdmconfig
140,141
Xrescources 141
Xservers
141
DMA 11
dmesg 11
dpkg 112
du
45
dump 50
dumpe2fs
43
E
e2fsck 43
echo 57
egrep 121,122
env
58
eregex
?
121
+
121
|
121
exec
65
expand
92
export 58
ext3
50
F
fdisk 31
fg
85
fgrep 122
FileAttributes 49
fileglobbing 67
files
isapnp.conf
12
/dev/ttyS0
17
/dev/ttyS1
17
/dev/ttyS2
17
/etc/isapnp.conf
12
/etc/ld.so.conf
103
/etc/mtab
45
/etc/updatedb.conf 73
/proc/dma
11
/proc/interrupts
11
/proc/ioports 11
/proc/mounts 45
/proc/pci
11
/var/log/dmesg
11
filesystem
absolutepath 72
datablocks
42
ext2
42
ext3
42

______________________________________________________________________________________________

Page185

LinuxITTechnicalTrainingCentre

Index

______________________________________________________
inodes 42
permissions 46
relativepath 72
superblock
42
filesystemhierarchy(FHS)
basedirectories
41
essentialroot(/)subdirectories
40
find
72
fips
3
fmt
94
fsck
43
fsck.ext2
43
fstab 33
fstaboptions
grpquota
34
noauto 34
owner 34
rw,ro 34
user 34
users 34
usrquota
34
G
gdm
140
grep 121,122
H
head 91
hexdump
92
history 63
hotplug
13
I
I/Oaddress 11
immutable
50
IRQs 11
isapnp 12
isapnptools
12
ISDN 20
isdn4kutils 20
J
jobs
86
join
94
K
kdm 140
kill
83
killsignals
SIGHUP,SIGINT,SIGKILL.SIGTERM 83
killall 84
L
LD_LIBRARY_PATH 103
ldconfig
102
ldd
102
ln
75
locate 73
ls
73
lsattr 49

lspci 11
lsusb 13
M
make 107
Makefile
100,106
man 66
Manpages
65
MANPATH
66
MBR 31
Metacharacters
commandsubstitions
`command`
63
$(command)
63
fileglobbing, 62
quotes
``
63
''
63
""
63
range
[]
62
{string1,string2} 62
wildcards
?
62
*
62
mkdir 74
mke2fs42
mkfs 42
mkfs.ext2
42
modem17,92,164
mount 33,45
mv
75
N
networkcards 15
nice
84
nl
92
nohup 86
O
od
92
Orlovblockallocator 50,52
P
partitioningscheme 5
Partitions
extended
28
logical 28
mounting
33
namingconvention 28
primarypartition
28
root(/) 40
unmounting 34
paste 94
PID
82
pnpdump
12
PPPoE 20
pr
95

______________________________________________________________________________________________

Page186

LinuxITTechnicalTrainingCentre

Index

______________________________________________________
ps
82
pstree 82
pwd
72
Q
quotas
aquota.user 35
edquota
35
grace 35
quota 35
quotacheck
35
quotaon
35
quotastats
35
repquota
35
usrquota
35
/etc/fstab
35
R
rawrite 2
redirectionandpipes
2>
61
2>&1 62
tee
62
<
60
<<
64
>
60
>>
60
|
61
regex
^
121
.
121
*t
121
\<
121
$
121
renice 85
rescuemode 4
resourceallocation
11
rm
74
root(/) 5
rpm
majormode 108
minormode 108
packageintegrity
110
packagenames
108
packagesignatures 109
querymodes 108p.
S
SCSI
booting
15
Channel
14
DeviceID
14
LUN 14
SCSIID
14
scsi_info
15,26
/proc/devices 28
/proc/scsi/scsi
15

sed
123
set
58
settingupmodems
16
COM1 17
COM2 17
COM3 17
setserial
17
wvdial 18
/dev/modem 18
SGID 49
sndconfig
22
sort
94
split 92
startx 139
stderr 59
stdin 59
stdout 59
stickybit
49
SUID 48
sync 50
synchronous 50
systemconfignetwork
20
T
tac
90
tail
91
tailmerging 51
tee
62
top
83
touch 76
tr
95
tune2fs
34
U
umask 47
umount
34
undeletion
51
unexpand
92
uniq 93
updatedb
73
USB
EHCIehcihdc.o
13
OHCIusbohci.o
13
UHCIusbuhci.o
13
usb.agent
14
usb.usermap 14
usbmgr
14
usbmodules 26
/etc/hotplug 13
/etc/usbmgr/ 14
USBSupport 13
V
vi
a,A,i,o,O,s,S 129
b,e,),},w
128
c,r
129

______________________________________________________________________________________________

Page187

LinuxITTechnicalTrainingCentre

Index

______________________________________________________
d,dd,x,p
129
h,j,k,l 128
u,^R(undo,redo)
130
y
130
^,$,1G,G
128
:!
131
:quit,:q!,:wq,:exit,:x,:e,ZZ
/,?
130
W
wc
91
whatis 65
whereis
which 73
winmodems
X
xauth 139

73
19

131

Xclients
Xdefaults
Xdefaults
xdm 140
xdm 139
xf86config
XF86Config
XF86Setup
xhost 138
xinit 139
xinitrc 139
Xresources
Xsession
xvidtune
Z
zombie 144

139
135
138

136
135p.,137
136

135,138
139
136

______________________________________________________________________________________________

Page188

You might also like