Sie sind auf Seite 1von 147

GettingStartedwith LinuxCourseMaterial

UdruenjeLinuxkorisnika (c)2005. Materialfromwww.linux.orgsite withpermissionfromauthor

Table of Contents
LessonOne....................................................................................................................4 Objectives..................................................................................................................4 PreparationWhatisLinux?....................................................................................4 InstallingLinux..........................................................................................................7 Anactualinstall.........................................................................................................9 DebianGNU/Linux..................................................................................................10 LessonTwo..................................................................................................................13 InstallationofDebianGNU/Linux..........................................................................13 LessonThree...............................................................................................................21 WorkingwithLinuxFirstThingsFirst.................................................................21 VirtualTerminals.....................................................................................................22 LessonFour..................................................................................................................24 Creatingyour'routine'inLinux...............................................................................24 ShellsinLinux.........................................................................................................24 TheLinuxfilesystem..............................................................................................25 InLinux,everythingisafile....................................................................................27 LessonFive..................................................................................................................30 DaytodaywithLinux.............................................................................................30 TexteditorsinLinux...............................................................................................31 Viforbuddingpowerusers.....................................................................................34 LessonSix.....................................................................................................................37 FrequentlyUsedShellCommands..........................................................................37 LessonSeven................................................................................................................44 PlumbingwithpipesinLinux..............................................................................44 Redirections.............................................................................................................44 LessonEight.................................................................................................................46 HowtogetmoreinformationwithLinux................................................................46 LessonNine..................................................................................................................48 Otherinterestingandusefulcommands...................................................................48 LessonTen....................................................................................................................51 Powerusercommands.............................................................................................51 Othercommands......................................................................................................51 Miscellaneouscommands........................................................................................53 Anintroductiontoaliases........................................................................................55 LessonEleven...............................................................................................................57 AnotherLookatUsers.............................................................................................57 FilepermissionsinLinux........................................................................................59 'chmod'explained.....................................................................................................61 Usingchown............................................................................................................64 LessonTwelwe.............................................................................................................65 Takingcarewhenworkingasroot...........................................................................65 2

Becomingasuperuser.............................................................................................67 Commandstocontrolyoursystem..........................................................................69 'top'...........................................................................................................................71 LessonThirteen............................................................................................................73 FilesystemsinLinux...............................................................................................73 Mountingfilesystems..............................................................................................74 /etc/fstab...................................................................................................................77 LessonFourteen...........................................................................................................78 Shellscripts..............................................................................................................78 The'.bashrc'file.......................................................................................................78 LessonFifteen..............................................................................................................80 Backingupyourfiles...............................................................................................80 Untarringandunzippingfiles..................................................................................81 Othercompressiontools..........................................................................................82 LessonSixteen..............................................................................................................83 InstallingNewPrograms.........................................................................................83 DebianUpdates........................................................................................................85 InstallingnewprogramsonSlackware....................................................................86 LessonSeventeen..........................................................................................................88 AutomationofTasksonLinux................................................................................88 LessonEighteen...........................................................................................................93 Networking..............................................................................................................93 Otherconfigfiles.....................................................................................................93 LessonTwenty..............................................................................................................96 Compilingkernel.....................................................................................................96 LILOandGRUB...................................................................................................100

Lesson One
Objectives
Wehavedevelopedthiscourseforonbasicreason:TobringthenewcomertoLinux tothepointwhereyoucandoeverythingthatyoudowithMSWindows,inLinuxand muchmore.Duetothefactthat Microsoft,enjoyinganillegalmonopoly,hasits operatingsysteminstalledon90%oftheworld'scomputers,thiscourseismainly aimedatpeoplewhowanttomigratetoLinuxfromMicrosoftproducts. ThesimplefactthatyouaregettingthiscourseofftheInternetpresupposesthatyou knowhowtouseaPC.Thecourseshouldbeorientedtowardspeoplemigratingfrom otherOSesandinparticular,MSWindows9x,ME,2000andXP. Ourobjectivesare: 1. To explain the differences between working with Linux and working with otherpopularOSes. 2. TostressthatthesomewhatsteeperlearningcurveinLinuxwillpaybackin theamountofstabilityandflexibility. 3. ToshowyouthatbyusingLinux,youhaveopenedupawholenewworldof computing.Thatistosay,youtheLinuxuserarenotjustapassivesubject reactingtowhattheOSletsyoudobutisanactive"developer"andcanmold theOStowhatyouwant.

Preparation What is Linux?


Linuxisanoperatingsystemthatevolvedfroma kernel createdbyLinusTorvalds whenhewasastudentattheUniversityofHelsinki.Generally,itisobvioustomost peoplewhatLinuxis,however,bothforpoliticalandpracticalreasons,itneedstobe explainedfurther.TosaythatLinuxisanoperatingsystemmeansthatit'smeanttobe usedasanalternativetootheroperatingsystemslikeMSDOS,thevariousversions ofMSWindows,MacOS,Solarisandothers.Linuxis not aprogramlikeaword processorandisnotasetofprogramslikeanofficesuite.

A brief history of Linux


When LinusTorvaldswasstudyingattheUniversityofHelsinki,hewasusinga version of the UNIX operating system called 'Minix'. Linus and other users sent requestsformodificationsandimprovementstoMinix'screator,AndrewTanenbaum, 4

buthefeltthattheyweren'tnecessary.That'swhenLinusdecidedtocreatehisown operatingsystemthatwouldtakeintoaccountusers'commentsandsuggestionsfor improvements.

Free Software pre-Linux


Thisphilosophyofaskingforuserscommentsandsuggestionsandusingthemto improve computer programs was not new. Richard Stallman, who worked at the MassachusettsInstituteofTechnology,hadbeenadvocatingjustsuchanapproachto computer programming and use since the early 1970's. He was a pioneer in the conceptof'freesoftware',alwayspointingoutthat'free'means'freedom',notzero cost.Findingitdifficulttocontinueworkingunderconditionsthathefeltwentagainst hisconceptof'freesoftware'heleftMITin1984andfoundedGNU.Thegoalof GNU was to produce software that was free touse, distribute and modify. Linus Torvalds'goal6yearslaterwasbasicallythesame:toproduceanoperatingsystem thattookintoaccountuserfeedback.

The kernel
Weshouldpointoutherethatthefocalpointofanyoperatingsystemisits'kernel'. Withoutgoingintogreatdetail,thekerneliswhattellsthebigchipthatcontrolsyour computertodowhatyouwanttheprogramthatyou'reusingtodo.Touseametaphor, ifyougotoyourfavoriteItalianrestaurantandorder'SpaghettiallaBolognese',this dishislikeyouroperatingsystem.Therearealotofthingsthatgointomakingthat dishlikepasta,tomatosauce,meatballsandcheese.Well,thekernelislikethepasta. Withoutpasta,thatdishdoesn'texist.Youmightaswellfindsomebreadandmakea sandwich.Aplateofjustpastaisfairlyunappetizing.Withoutakernel,anoperating systemdoesn'texist.Withoutprograms,akernelisuseless.

1991, a fateful year


In1991,idealconditionsexistedthatwouldcreateLinux.Inessence,LinusTorvalds hadakernelbutnoprogramsofhisown,RichardStallmanandGNUhadprograms butnoworkingkernel.Readthetwomen'sownwordsaboutthis: Linus:"Sadly,akernelbyitselfgetsyounowhere.Togetaworking systemyouneedashell,compilers,alibraryetc." RMS:TheGNUHurdisnotreadyforproductionuse.Fortunately, anotherkernelisavailable.[Itiscalled]Linux. So combining the necessary programs provided by GNU in Cambridge, Massachusettsandakernel,developedbyLinusTorvaldsinHelsinki,Finland,Linux wasborn.Duetothephysicaldistancesinvolved,themeansusedtogetLinus'kernel togetherwiththeGNUprogramswastheInternet,theninitsinfancy.Wecansaythen thatLinuxisanoperatingsystemthatcametolifeontheInternet.TheInternetwould 5

alsobecrucialinLinux'ssubsequentdevelopmentasthemeansofcoordinatingthe workofallthedevelopersthathavemadeLinuxintowhatisistoday.

Linux is introduced
Late in 1991, Linus Torvalds had his kernel and a few GNU programs wrapped arounditsoitwouldworkwellenoughtoshowotherpeoplewhathehaddone.And that'swhathedid.ThefirstpeopletoseeLinuxknewthatLinuswasontosomething. Atthispoint,though,heneededmorepeopletohelphim.Here'swhatLinushadto saybackin1991. "AreyouwithoutaniceprojectanddyingtocutyourteethonanOS youcantrytomodifyforyourneeds?...Thispostmightjustbefor you." Peopleallovertheworlddecidedtotakehimuponit.Atfirst,onlypeoplewith extensivecomputerprogrammingknowledgewouldbeabletodoanythingwiththat earlypublicversionofLinux.Thesepeoplestartedtooffertheirhelp.Theversion numbersofLinuxweregettinghigherandhigher.Peoplebeganwritingprograms specifically to be run under Linux. Developers began writing drivers so different videocards,soundcardsandothergadgetsinsideandoutsideyourcomputercould useLinux.Nevertheless,throughoutmostoffirstpartofthe1990'sLinuxdidnotget outofthe'GURU'stage.GURUisatermthathasevolvedtomeananyonewhohas specialexpertiseinaparticularsubject.Thatis,youhadtohavespecialexpertisein howcomputersworkedtobeabletoinstallLinuxinthosedays.

Linux, at first, not for everybody


OtherpopularsoftwarecompaniessoldyouaCDorasetoffloppiesandabrief instructionbookletandinprobablylessthanahalfanhour,youcouldinstallafully workingoperatingsystemonyourPC.Theonlyabilityyouneededwasknowinghow to read. Those companies had that intention when they actually sat down and developedtheiroperatingsystems.LinusTorvaldsdidn'thavethatinmindwhenhe developedLinux.Itwasjustahobbyforhim.Lateron,companieslikeRedHatmade ittheirgoaltobringLinuxtothepointwhereitcouldbeinstalledjustlikeanyother operatingsystem;byanyonewhocanfollowasetofsimpleinstructions,andthey havesucceeded.Forsomereason,though,Linuxhasn'tshakenoffcompletelythat 'Gurusonly'imagethatittookonatthebeginning.Thatismostlytheresultofarticles in the popular,quasitechnical press whose experience withLinux has been quite limited.

Linux Today
Today,Linuxisenjoyingafavorablepressforthemostpart.Thiscomesfromthefact thatLinuxhasproventobeatremendouslystableandversatileoperatingsystem, 6

particularly as a network server. When Linux is deployed as a web server or in corporatenetworks,itsdowntimeisalmostnegligible.Therehavebeencaseswhen Linuxservershavebeenrunningformorethanayearwithoutrebootingandthen onlytakendownforabriefperiodforroutinemaintainance.Itscosteffectivenesshas solditmorethananythingelse.LinuxcanbeinstalledonahomePCaswellasa networkserverforafractionofthecostofothercompanies'softwarepackages.More reliabilityandlesscostit'sideal. Ifyou'rereadingthis,you'reobviouslyheretolearnhowtouseLinux.Anylearning experience means opening up to new ideas and new ways of doing things. As mentioned before, Linux is in the UNIX family of operating systems. UNIX is primarilydesignedtobeusedbyprofessionals.YouwillhavetolearnsomeUNIX concepts in this lesson, but that doesn't mean that Linux is a professionalsonly operatingsystem.Quitethecontrary.MostmajorversionsofLinuxaredesignedtobe asuserfriendlyandaseasytoinstallasanyotheroperatingsystemonthemarket today. NowthatyouknowwhatLinuxisandhowgooditis,there'sonemorethingwehave todoinstallLinux!

Installing Linux
Some preliminary considerations
There are many different versions of Linux. Unlike other commercial operating systemsthatarecontrolledbyonecompany,Linuxisfreetodistributeanduse.So,in theLinuxworld,thereisasituationunlikewhatoccursintheproprietaryoperating systemworld:anumberofcompanies,organizationsandindividualshavedeveloped theirown"versions"oftheLinuxoperatingsystem,knownasdistributions.Thereare versionsofLinuxthatweredevelopedtobeinstalledoncomputersthatreceiveheavy traffic, so to speak, like webpage servers. Some were developed to be used in networks were security is a priority; where sensitive information should only be accessed by a privileged few. There are versions of Linux that are meant to be installedontopofanexistingoperatingsystemlikeWindowssopeoplecantryout Linuxunderfamiliarconditions.ThereareversionsofLinuxthataredesignedtobe installedonplatformslikeMacintosh.ThereareversionsofLinuxwithfunnynames like"ChainsawLinux"(nokidding)and"TuttiFruttiLinux"(yes,it'sajoke).

What Linux is right for me?


This is a very difficult question to answer. To use an analogy, if I were going mountainclimbing,Iwouldneedspecificclothestoprotectmefromscrapes,thecold, wind,rainandotheradverseclimacticconditions.IfIweregoingtoaformaldinner,I wouldneedatuxedo.IfIweregoingaboutmydailyroutine,Iwouldwere"normal" 7

clothes. There are computer world equivalents of mountain climbing and formal dinnersaswell asjust sittingaroundthehouse. Linuxhas beenfitintoallthose environmentsandmore.ThereiseventheequivalentofaswimsuitinLinuxavery scaleddownversionjusttocovertheessentials. MostPCusersprobablyjustneedtheeverydayversion.ThiskindofLinuxhasbeen widelyavailableforsometimenow.UnfortunatelyMicrosoftCorp.,whomakesits livingsellingpeople"ordinary"operatingsystems,havealottoloseifLinuxevergot popularwiththemasses.Forthisreasontheyhavedoneeverythingintheirpowerto "warn"thepublicthatLinuxissomethingthatyouprobablydon'twantanddon't need.Butinreality,Linuxisjustaseasilyinstalledandsupportsjustaswidearange ofhardwareasMicrosoftWindowsdoes.ThePRdepartmentatMicrosoftiscoming upwithfewerandfewerreasonsnottouseLinux.Addtothisthefactthatinthelast yearorsothreemajor"distributions"haveemergedthatcaterspecificallytothenon technicaluserandyoucanseethatLinuxhastrulyachievedthegoalofbeingall thingsforallpeople.

Linux on Pcs containing Intel-based CPUs


ItwouldbeimpossibletocoverallofthedifferenttypesofLinuxsothislessonwill onlydealwithstandardversionsofLinuxthataremeanttobeinstalledonPCswith IntelbasedCPUs.Youmayhaveheardofsomeofthecompaniesandorganizations thathavecreateddistributionsforthisplatform,likeDebian,Mandrake,RedHatand SuSE . There are others as well. There are even versions of Linux that offer documentationandinstallprogramsinlanguagesotherthanEnglish.Weshouldsay herethatitisnotourintentiontoendorsetheproductsofthecompanieswehave mentionedherenordowewanttoslightthosecompaniesthatwehaven'tmentioned. LinuxOnlinemaintainsa listofallkindsofdistributions.Weinviteyoutoconsult thatlistbeforedecidingoninstallinganyversionofLinux.

Prepare your manuals


Aswementionedbefore,themajorversionsofLinuxhaveperfectedtheirproductsto suchadegreethattheyareveryeasytoinstall.Welldesignedprogramswilltakeyou throughtheprocessofinstallationstepbystepsothatyouwillbeabletogetLinuxup and runninginarelativelyshortperiodoftimewithoutanyheadaches. Buteven commercialoperatingsystemsthatarebilledasbeingthemostuserfriendlyinthe worldcan'tguaranteea100%problemfreeinstallation. ThebestthingtodobeforeattemptingtoinstallLinuxistogetthemanualsthatcame withyourPCoutoftheclosetanddustthemoff.MajordistributionsofLinuxhave takenintoaccountmoststandardhardwaresuchasvideocards,modemsandsound cards,butaswesaidbefore,nobodycanguaranteeaproblemfreeinstallationforany operating system. Thoughyou probably won't need them, they may help to track 8

downaproblemorpreventafutureone.Now,gogetthosemanuals,andwe'llmeet youinthenextlesson!

An actual install
MostreputablePCresellerswillhandyouastackofmanualswhenyoubuyyour machine.Butlet'simaginethatyougotahandmedownPCfromyourbigbrotheror sisteroryoupickedupyourPCatagaragesaleoryougotthePCfromsomeother sourcethatwereallydon'twanttoknowabout.Youmaybeluckierthanyouthought. LinuxwillactuallyinstallmoreeasilyonolderPCsthanonsomenewerones.Then again,itdependsonhowolditis.Don'ttrytoinstallLinuxononeofthoseoldPCs withamonochromemonitorwhereeverythingcomesoutayuckygreencolor.That's TOOold!

Do you want a 'Dual-boot' system?


OK,withorwithoutmanuals,nowit'stimetoinstallLinux.You'vegotyourversion ofLinuxandyoujustcan'twaittouseit.Butthereareacoupleofquestionsyouneed toaskyourself. 1. Doyouhaveanotheroperatingsysteminstalled. 2. Doyouwanttocontinuetouseit. Ifyouwanttokeepanexistingoperatingsystem,andinstallLinuxaswell,youwill havewhatisknownasa"dualboot"system.ThatmeansthatyouhaveaPCthatcan usetwodifferentoperatingsystems.IthinkthatIshouldpausehereandsaythat everythingthatyoucandowithyourgardenvarietyoperatingsystem,youcando withLinux.Thatmeanswordprocessing,databases,spreadsheets,Internetbrowsers, email,phototouchups,MP3,CDPlayers,camerasandthentherearealotofthings that Linux has to offer on topof all that that other operatingsystems don't. The importantthingisthatyouhavetheoptiontohaveboth.Now,backtotheinstall.

Downloading Linux
OneofthemostmisunderstoodconceptsofLinuxisthatitiswidelyspokenofnotso muchasa"free"operatingsystembutasa"freebie"operatingsystem.'What'sthe difference?' you may ask. The "free" ideally refers to the source code of Linux. Microsoft won't give you the source code to their products so you can make improvements(andweallknowhowmuchtheyneedthem),butthemajorityofLinux distributions come with the source code or at least for the programs that aren't proprietary. The"free"thatmostpeoplethinkofisthefreeof"freebie"or"handout".Thisis somewhatfictitious.Thetruthisthatthereisnothinginthisworldthatcomesatzero cost.IfyouhappentohaveafastInternetconnectionandaCD burner,youmay 9

download ISO imagesoftheLinuxdistributionyouhavechosen(andthatletsyou havethemfreeofcharge),butithascostyoumoneyfortheCDsandyourtime(the costliestthingofall).Linuxreallyshouldneverbetoutedasazerocostoption,but betterasanoperatingsystemthatcanbeobtainedandmaintainedataverylowcost. Ifyoudon'thappentohaveafastconnectionandaCDburner,youcanstillgetLinux, though,atatverylittlecost.Youcanpickupaniceboxedsetfromthemakersof commercialdistributions.PersonalPCuserscanpickupaniceoperatingsystemfor homeuseforaround3050USdollars.Theseusuallycomewith90daysoftech support,viaemail,inmostcases.YoucanalsogetLinuxfromPCmagazinesthatwill often provide CDs of the major Linux distributions and some basic installation instructionsforjustthecostofthemagazine. Our pick for an example walkthrough installation and setup with be Debian GNU/Linux.

Debian GNU/Linux
Asitwouldbeimpossibleinthiscoursetotalkaboutandgiveinstallationinstructions foralloftheLinuxdistributions,wehavechosenDebianGNU/Linuxforanexample install.Whyhavewechosenthisdistribution? Itis: 1. Asolid,qualityLinuxdistributionwithalonghistory(inLinuxterms) 2. Nonprofitandnoncommercial(whichletsusoffthehookonalotofissues!) 3. Applicabletoawiderangeofusesandusers,fromnewcomertoseasonedIT professional. 4. Easilyobtainedandupdated.

About Debian
The DebianprojectwasfoundedbyIanMurdockin1993.It'snamecomes from Debra,hiswifeandhisname(DebIan:ergo,Debian).OneoftheLinuxworld'smost illustriouspeoplehasbeenaprimarydeveloperofDebian,namelyBrucePerens.He wasoneofthefoundersofPixar,thecompanythatcreatedanimatedfilmssuchas ToyStory,Monsters,Inc.andotherpopularfilmsproducedbyWaltDisneyPictures. Debianhasnocompanybehindit.TheDebianprojectissponsoredbySoftwareinthe PublicInterest,anonprofitorganizationdedicatedtohelpingproduceopensource softwareandhardware.Despiteitsnotforprofitstatus,Debiancanandisbeingused fromanythingfromaPentium3youcansurfthewebwithtothemissioncritical serverthathastobeup24/7thatyougetthecontentfrom.Wecanalsoaddalotin between.

10

Thoughtheinstallationprocedureisnotaseasyassomecommercialdistributions,it cannotbedescribedasdifficulteither.Wewillgooverthisinmoredetailshortly.The majoradvantagetoDebianisthatitcanbeupdatedeasilyviatheirmuchlaudedapt getsystem.

Getting Debian GNU/Linux


Ifyouhaveabroadbandconnection(cable,xDSLorbetter),youcaneasilyobtainthis distributionandinstallit.Therearetwomajorwaystodothis.Themostpopularisto burntheDebianISOimagestoCDsandinstall.IfyouhaveaCDburner,thisisan idealoption.ThesecondistoobtainaminimalISOimageespeciallydesignedfora installovertheInternet(ie,downloadingthefilesastheinstallerneedsthem).This canalsobedonebydownloadingfloppydiskimagefilesinsteadofCDimages.More informationonthesemethodscanbefoundathttp://www.debian.org/distrib/ Ifyoudon'thappentohaveabroadbandconnection,downloadingDebianwouldbe an extremelyfrustrating experience.Youmaywant toconsider contactingalocal distributorofDebianCDs.Consultthispageforfurtherinformationaboutdistributors inyourarea:http://www.debian.org/CD/vendors/

Installation from CD
ThisisprobablygoingtobethemostcommonwayofinstallingDebian,sowego overinstallationusingthismethod.

Preliminary considerations
Youmaybewonderingifyoucankeepanotheroperationsystem(ie.MSWindows whichotheroneisthere?)onyourcomputer.Youcan. Arewegoingtoexplainhowtodoit?Notingreatdetail.Why?Thereareacoupleof reasons: LackofexperiencewiththenewerMicrosoftproducts. Theauthormustadmitthathe'sinstalledagreatnumberofLinuxdistributions sidebysidewithWindows9.xproducts.Hehasn'tdoneitwithanyofthe morerecentones,soadviceondoingitwouldbeofdubiousquality. There'snothingyoucandowithMicrosoftproductsthatLinuxwon'tlet youdoaswell Enoughsaidthere.Please,beforeyouflamethepoorauthor:Hedidnotsay thatitwouldbeeasierwithLinux.Sometimesitis,asamatteroffact. Wedon'tworkforMicrosoft WeadvocatealternativestoMicrosoftproductsandnotthecontinueduseof them,evenina"secondfiddle"role.

What we can say about dual-booting


11

IfyouhappentohaveMSWindows9.xyoumustrepartitionyourharddrivetomake roomforLinux.Youcaneithererasethedriveandrepartitionablankdriveoryoucan attempttorepartitionaworkingharddrive.Ideally,whatwasdoneinthe"old"days wastoinstallWindowsinC:andD:partitions.Thisisrelativelyeasytodealwith.As amatteroffact,myfirstinstallofSlackwareLinuxwasontheD:partitionofmy Windowsworkstation. If you've got one partition with Windows on it, there are some supposedly non destructive resizing tools. They always tell you to back up your data before proceeding,soIalwaysfigurewhat'stheuseinresizingwhenyoucanstartclean fromscratch.YoumaydecideyouwanttothrowawayWindowsalltogether! Summingup,IrecommendLinuxonlyinstallations.Linuxhasbecomequite"mature" asanenduseroperatingsystem,soIfindthesestoriesaboutbeing"weaned"off Windowstoberidiculous(theexception,supposedly,beingthosewhorunthe financialsoftware'Quicken').Ifyou'veboughtanewcar,youdon'thavetobe "weaned"offthat.Youjusttradeintheoldoneandstartdrivingthenewone.The graphicuserinterfacesavailableplustheevergrowingnumbersofproductivity applications(officesuites,browsers,emailapplications,etc.)makeitsuchthataMS Windowsusercouldhavehis/herworkstationswitchedwithaLinuxmachine overnightandtheywouldbarelybreakasweatgettingusedtoit.Everythingworks verymuchinthesameway.

12

Lesson Two
Installation of Debian GNU/Linux
Booting from a CD
Chancesare,ifyourPCislessthan5yearsold,youcanstartaLinuxinstallationright fromtheCDROMdrive.Thewaytofindoutistolookatyourcomputer'sBIOS. There'sreallynoneedheretogointowhatyourBIOSisorwhatitdoes.Let'sjustsay thatit'sthereandyouneeditforyourcomputertowork.Whenyouturnonyour computer,there'salittlemessagethatsays'PressDELtoentersetup'.Anythingthat mentionsthewordDELusuallyscarespeople.Itshouldn't.PressingDELwhenyour computerbootsupwilljustgetyouintotheBIOSsetuptools.Itwon'tgetyouinto trouble,unlessofcourseyoustartpressingbuttonsrandomly.You'llseeabluescreen popupwithsomemenuitems.Whatyouneedtoselectistheitem'BIOSFEATURES SETUP'You'llseesomemoremenuitems.There'sonethatsays'Bootsequence'. That'stheoneyouwant.Ifyouusethepageup/pagedownkeys,youcansetthisitem sothatitsaysCDROMfirst.ThatjustmeansthatitwilllookforthediskinyourCD ROM drive first when the computer boots. Press ESC and then choose the item 'SAVEANDEXITSETUP'.Don'tforgettosetitbackto'C'whenyou'refinished installingLinux.We'llremindyoulater. Ifyoucan'tbootfromyourCDthere'sanoptiontocreateabootfloppy.Inyour machine'sBIOS,youmightjustseeA,CC,Aandthere'snoCDROMmentioned there.Don'tpanic.Youcanmakeabootfloppy.Theyoftencomewithboxedsets,but ifyouyoursdidn'tcomewithone,we'llcoverhowtocreateonefurtheralong.

Partitioning
Yourharddiskislikeapie.Youcandivideitintosections.Unlikeapie,afteryou've dividedit,youcan'tgiveapiecetothedog.Mydogdidtrytoeatmyharddiskonce and he really relishes the floppies I leave lying around, but alas, I digress. For example,ifyouhadtwopartitions,popularoperatingsystemswouldgenerallycall themCandD.YoucancallthemGingerandFred,orGingerandMarianneoreven theProfessorandMarianneifyoulike.Ijustusethesebadjokesasawayofsaying thatCandDarenamingconventionsthatbelongtootheroperatingsystems.Linux doesn'tusethem.Linuxmaycallthem/hda3and/hda5forexample.We'llgettothat inaminute.Thenyouwillneedanotherpartitionknownasa'swap'partition.This 'swap'partitionisjustawaythatLinuxusestogetmorememorysothatyoudon'trun outofit.

13

Theclassicwayofpartitioningyourharddiskiswithaprogramcalled'fdisk'.The programcomeswithalotofwhistlesandbuzzersandflashingmessagesthatsay "Danger,WillRobinson".There'saversionforLinuxandbutitdoesn'tmentionWill Robinson.WewanttosayherethatthisistheSWATteammethodofdoingitthe scorchedearthpolicyofpartitioning.Ifyouhavethatimportanttermpaperonyour harddisk,orpicturesofthatdreamvacationtoHawaiithatyouhaven'tshowntoyour AuntBettyyetoryourbestDOOMscores,you'llneedtomakebackupcopiesof them.Therepartioningusingthismethodwillgetridofthemforever![cueominous organmusic]. ButinstallingLinuxisn'tdangerousandifyouchoosetoinstallyoumaynotneed suchadrasticsolutiontoyourpartitionproblem.Aswementionedbefore,Ifyou're fortunateenoughtohaveaharddrivewithmorethanonepartition(theoldC:andD: routine),thenitmaybejustaquestionofmovingsomefilesaround.Unfortunately thislessoncan'ttakeintoaccounteverybody'sindividualcircumstances. There'satoolcalledFIPSthatcomeswithmajorLinuxversions.Thiswillrearrange yourharddrivesoyoucaninstallLinux.Therearealsoothercommercialproducts thatwilldothesame.Thatmaybeanoptionforyou,unlessyou'vegotaharddrive that'sburstingattheseams.YoushouldknowthatanydecentworkingLinuxsystem andbydecent,Imean,havingtheprogramsthatwillletyoudoanythingyoudidwith yourWindowssystemwilltakeatleast2gigabytes.Pleasekeepthatinmind.Andif youwantthosephotosofHawaiionthere,I'dplanforabitmore. TotalkaboutwhereLinuxandotheroperatingsystemsshouldgo.Inanysituation whereyou'vegottwothingssharingthesamespace,liketwopeoplesharingthesame apartment,onepersonwillalwaysexerthisrightsovertheother.Otheroperating systemsusuallywanttobetheonlyonesinthecomputer,soeventhoughit'sreally notgoingtobethisway,youhavetoinstalltheminthefirst'primary'partition,and thatwayitthinksit'stheonlyonethere.Thatmeansinstallingitin/hda1inLinux speak.Soremember,ifyou'vechosentogothefdiskroute,theotheroperatingsystem shouldbereinstalledfirst.Whenyou'vegotthatreinstalled,youarefreetoinstall Linux in what's left. Once you've installed Linux, you can actually see the other system'spartition,sortoflikethosephonymirrorsatthesupermarket.We'lltalkmore aboutthatinanotherlesson.

Plunk that CD in the drive


Okay.Nowisthemomentoftruth.We'vegottheCDinthedrive,andwe'rereadyto go.Restartthecomputer.ThisshouldnowboottheLinuxkernellocatedonyourCD ROM. Whatyou'llhavetodofirstispartitiontheharddrive.Thereisaneasywaytodothis. YoucandedicatethewholeharddiskornonWindowspartition(dependingonthe typeofinstallyou'redoing).Thereisabetteralternative.Thatistopartitionyourhard 14

diskevenfurtherandput"parts"ofLinuxonseparatepartitions.Forexample,thisis theschemethatworksforme: Let'stakea10gigabyteharddriveasanexample.First,youshouldseehowmuch RAMyouhave.Fromthisfigure,youcreatewhat'sknownasaSWAPpartition.This issimplyawaythatLinuxusestogetanextramemoryboost.Customdictatesthat yourswappartitionbedoubleyourrammemory.Soifyou'vegot256megabytesof RAM,thefeelfreetomakea500megabyteswappartition.Thenmypartitionscheme endsuplookinglikethis:

Partition swap /(boot) /usr /home

Location /dev/hda2 /dev/hda1 /dev/hda3 /dev/hda4

Size 500mb 1.2gb 3.5gb 5gb

Assignpartitionstolooklikethis.Don'tworryaboutthe/usrand/homeparts.That willcomeafter.Youmustindicateherethatyouwant/tobethebootablepartition./ usr willcontain most of theprogramsthat willrunonyourmachine./homewill containyourpersonalfiles.Thiskindofapartitionschememaycomeinhandyifyou haveproblemswithyourharddisk.Youmaybeabletosaveinformationifit'slocated indifferentpartitionseasierthanifitwereonlyonebigpartition. Beforeweactuallyassigntheotherpartitionstheirplacesandfunctions,weneedto initializeandactivateatheswappartition.Dothisnow. Nowyoushouldinitializethe/partitiontheonethatwillboottheLinuxkernel. Now,thereiswhatIconsideralittleglitchintheDebianinstall.Itdoesn'treallytake intoaccountthatyouwanttoinitialize/usrand/homepartitions.Don'tgotothenext stepyet.Youshouldgobackandinitializethesepartitionsnowbeforeproceeding.

Sundry installation tasks


Atthispointyoushouldhaveyourharddrivepartitionedandthesepartitionsassigned towhatareasthey'llbehousing. Now, comes thepoint intheprocess to installtheLinuxkernel.Youcanchoose additionalpartstoaddtothekernel,knownasmodules,tobetteruseyourhardware. Debiandoesaprettygoodjobofautodetectingwhatyouhave,sothereshouldn'tbe

15

anyneedtotouchanythinghere.Peoplewhoknowthatthey'regoingtohavetouse foreigncharacterfontsmaywanttoaddadditionalsupportforfontsets. At thispoint,you'llhavetochoosea'hostname'ornameforyourcomputer.Use whatevernamingschemeiscomfortableforyou.After,youshouldchoosea'domain' name. Even if your not running an Internet server and even if you don't have a networkyoushouldchooseanameasifyouhadone.Normallyifyouwereinfacta serverprovidingInternetservices,youwouldchooseanameandappend.com,.net etcontheend.Iwould,ofcourse,beanameregisteredwithanofficialdomainname registry.Inthecaseofasinglemachineoranetworkthat'sconnectedtotheoutside onlybywayofadialupconnection,youshouldchooseasinglenamewithoutthedot extension. Now you should enter your ISP's domain name server IPs. Each block (the four numberedsetseparatedbyperiods)shouldbeseparatedbyaspace. Now,aswe'reinstallingfromaCD,youshouldchoose'CDRom'fortheinstalation procedure.Youshouldalsochoosethesettings'makesystembootable'. Yourharddiskisbasicallyapieceofmetalwithametaldiskflyingaroundinitat incrediblespeeds.Itessentiallydoesnothingunlessyoutellittodo.Atthispoint, we'regoingtotellittobootuptheLinuxoperatingsystem.Ifyou'recontemplatinga dualbootsystem,youcanalsotellittoaskyoutochoosefromdifferentoperating systems at boot. Debian uses a program called 'LILO' to do this. Later, you can actuallymakealternativeversionsoftheLinuxkernelandhaveLILObootthem. Rightnow,yoursafestbetistoinstallLILOinthe'masterbootrecord'whenthe installprogramasksyou.The"MBR"isalittlesliceoftheharddiskpiereservedfor momentslikethis! Theprogramwillnowaskyoutocreatearescuefloppy.Thesewillcomeinhandy. Forexample,Ihaveoftenmadethefatalmistakeof*not*correctlyconfiguringLILO whenIhavemadeanewLinuxkernel(yes,youcanmakethemfromscratch!)andmy systemhasbecomeunbootable.Youcanalwaysrelyonarescuefloppytogetyouout ofthissituation. OK,now'sthetimetorebootthebasicsystemthatDebianhasinstalled.Youneedto removethefloppyandtheCDfromthedrives.Itmightbeagoodideanow,asyour machinereboots,togobackintotheBIOSandsetitbackforthemachinetoboot fromyourharddrivefirst(insteadoffromyourCDdrive).Butatleastmakesureto removetheCDorelseitwillboottheCDagainandstarttheinstallprocessagain.

Reboot and basic configuration


YournewDebianGNU/Linuxsystemisnowrebooting.Whenthat'sfinished,you'll havetoanswerafewquestionsaboutconfiguration. 16

You'llnowbeaskedifyouwanttouseMd5passwords.Withoutgettingintoalotof technicaljargon,Md5passwordsareprotectedwithanextralayerofsecurity.You should choose this if you think you'll be needing extra security. You'll have to evaluatethisonyourown.Ifyoudon'tchoosethis,you'llbeaskedifyouwanta 'shadow'passwordsystem.Onceagain,withoutgoingintoanytechnicaljargon,thisis anotherUnixschemeforextrasecurity.Youshouldalwaysanswer'yes'tothisone because without it, your password, especially if it's some dictionary word, would becomeveryeasytocrack.Bytheway,youshouldneveruseadictionarywordasa password. Aswe'reonthesubjectofpasswords,nowit'stimetoenterthepasswordforthe famous'root'account.'root'istheadministratorofthesystem.It'salsoknownasthe superuseraccount.We'llgetintomoredetailonthedutiesandprivilegesofrootlater on.Sufficeittosay,youshouldnowtypeinapasswordforthe'root'account.Please chooseonethat'seasyforyoutorememberbutwouldbedifficulttoguessor"crack". Forexample,ifIwereaStarTrekfan,ImightbetemptedtouseSpockasapassword. Spock probablyisn'tinthedictionary,butitmightbesowellknownnowthatit wouldbefoundinanyprogramthatcrackersusetogetintosystems.Therefore,I wouldchoosesomethingalittlelesswellknowninTrekloreandmodifyitsomewhat. TrekfanswillrememberthatmutantbratwhooncetriedtotakeovertheEnterprise, CharlieX.Well,'ch4rl13X'mightbeagoodpassword.Takingthesomelettersand replacing them with similar looking numbers. This is an acceptable password procedure.Thebestis,ofcourse,creatingarandomstringoflowercaseandcapital lettersandnumbersandjustrememberingit.'C2jl7y2B'isanexcellentpassword.Itis, however,difficulttoremember.Intheend,everybodycomesupwithhis/ownown schemethatworks. Nowyoushouldcreateanaccounttoworkwithnormally.WhatImeanby"normally" isthatLinuxisatruemultiusersystem,soonemachinecanbeusedbyhundredsof users.Wheneachlogsin,he/sheisrestrictedtomodifyingonlythefilesownedby him/her.Thisinsuresalotofsecurityandremovesalotofheadaches.Youshould neverdoroutineworkasroot.Thisaccountshouldbeonlyusedtoperformimportant administrativetasks.Feelfreetouseyourfirstnameorthefirstletterofyourname andyourlastnameastheloginforthisaccount.Followthepasswordconvention you'recomfortablewith. Now,you'llbeaskedtoremovePCMCIAfromthesystemifyoursdoesn'tuseit.Feel freetodoso. YouwillnowbeaskedifyouwanttoconfigureyoursystemtouseyourISP.Ifyou haveadialupconnection,thisisagoodtimetouseit.Ifyouconnectbywayof broadbandorbetter,youcanskipthispart.

17

Atthispoint,we'rereadytochoosetherestofthepackagesthatwillmakeupour Debiansystem.

Completing the install process


Nowit'stimetobegininsertingeachoneoftheCDsyouhave.Theywillbescanned foravailablepackagesforinstall.Thereisamaximumof8intheset.Inserteachone andwaituntilyouareaskedforanother. Whenyouhavecompletedthescanningprocess,youwillbeaskedtochooseanother 'apt'source.WithDebian,youcandownloadandupdatepackagesautomaticallyright offthisInternetwiththe'apt'system.Wewillconfigurethislater,rightnowit'sbest nottochooseanotheraptsourcebesidestheCDs. Atthispoint,ifyouareconnectedtotheInternetbywayofbroadbandforexample andtheinstallprogramcanmakeaconnectiontoDebian'ssecuritysite,itwillnow start searching that site for security updates. From the time the ISO images are releasedtothepointwhereyouareinstalling,securityflawsmayhavebeenfoundin certain programs includedwith Debian. For this reason acheckis made and any programswithflawsaremarkedandupdatedcopiesdownloadedandinstalled. Afterthesecurityupdatesarefinished,youwillbepresentedwiththepossibilityof doingasimpleinstallwithTheDebianTaskInstaller.Thiswillinstallprogramsafter youhaveindicatedyourgeneralpreferencesfromamenu. Ifyouaremoreadventurous,youmaychoosethemoreadvancedinstallprocessby wayofdselect.Hereyouwillchoosepackages"byhand"fromalistofhundreds. Thoughthedselectinterfaceisnotvisuallyappealingandmayappeardauntingto newcomers,itisfairlystraightforwardandisactuallyquiteuserfriendlyinthesense thatitisalmostimpossibletorunintotroublewiththepackagesyouwanttoinstall.If youweretochooseapackagethatconflictedwithsomethingelse,youarenotified. Thatway,youcaneitherchoosetokeepthepackagethatDebianrecommendsor"un select"thepackagesoyourownchoicecanbeinstalled.

At the fork(s) in the road


Herewereachtheendoftheinstallsection.Youwillhavetodosomemoreworkin thisdepartment,butduetothefactthatthepackageseachpersonmightchooseand thehardwareinhis/hermachine,wecan'treallydocumentaccuratelywhat'sgoingto goonfromhere.Ourinstallroadhasreachedaplethoraofforksinit.Somesimple advice:justanswerthequestionsasaccuratelyasyoucanandyoushouldbefine.

Post Install

18

We'llassumethatyou'vegotaworkingDebiansystemnow.Ifyou'vegotabroadband or betterconnectiontotheInternet,youshouldnowconfiguretheaptget system whichwillallowyoutoupdateyoursystemquicklyandpainlessly.Itwillalsoallow youtogetnewprogramsbydownloadingandinstallingthemautomatically. IfyouhaveabasicknowledgeofUnixcommandsalready,Youshouldgotothe directory/etc/apt/anddothefollowing(asroot).(Evenifyoudon't,youmaywantto tryit!) mv sources.list sources.list.old This renames the file sources.list to sources.list.old. sources.list is what told the 'dselect'and'apt'programswheretogetthepackagestobeinstalled.Nowwe'regoing tochangethingsabit.We'lltellthemtogetpackagesofftheInternetdirectly.We needtocreateanewsources.listfileandaddournewpackagesourcestoit.Dothis first: vi sources.list Thisbringsupthetexteditor'vi'.Therearepeoplewholovethisprogramsomuch, theywillchallengeyoutoapistolduelat20pacesifyoutellthemyouthinkit's lousy.IfyouhavezeroexperiencewithLinuxorUnix,'vi'isprobably*not*thetext editorforyouatthispoint,butwithafewsimplestrokesofthekeyboard,wecando whatwewantfornow. Hittheescape(ESC)keyandtheletter'i'andyourreadytoinsertthefollowing.
deb http://http.us.debian.org/debian stable main contrib nonfree deb http://non-us.debian.org/debian-non-US stable/non-US main contrib non-free deb http://security.debian.org stable/updates main contrib nonfree

YoumaywanttogotoDebian'shomepageandlookupsuitablemirrorsitesnearerto you.I'msurethepeoplewhomaintaintheDebianwebsitewouldappreciateittoo! Now,tosavethefile,hitESCagainand':'thetype'wq'(meaningwritequit)andyour fileissaved. Nowyou'rereadytokeepyourDebiansysteminshape.We'llgiveyouarefresher lateroninthecourse,butyouwillprobablybemakinguseofthesecommandswhile youuseDebian. willupdateyoursystemwiththelatestsecurityenhances packages.Use:aptgetupgradeshowupgradedtogetalittlemoreverbosereportof what'sgoingon.
apt-get update

19

apt-get --purge remove [program/package name]removesanytraceofa

programfromyoursystem.
apt-get install [program/package name]installsanewprogram.

Now,let'sseewhatwecandowiththatDebiansystem!

20

Lesson Three
Working with Linux First Things First
When you work as root
YouhavenowinstalledLinuxandthefirstthingyoudidwasloginas'root'.Thenyou providedapasswordsothatyouandONLYyoucouldlogintothesystemas'root'. Whenyoudecidetoworkasroot,youhadbettergointoaphoneboothfirstand changeinto abluesuit withabig 'S'onthefrontbecause'root' isknownasthe 'superuser'.(youcanskiptheredtightsifyouwant) That'sreallynotmeanttobejustawittyreferencetotheManofSteel.Actually,itis muchmoreglamouroustobe'Superman'butrootisactuallymorelikethe'janitor'of theLinuxsystem.Roothasthekeystoeverything,hecanshutoffthelights,shutoff theheat,lockyououtofthebuilding;hehastocleanupthesystemandintheend makesureeverythingruns.Andthemostimportantthingaboutbeingajanitorhe seeseverything.

'root' is not for routine work


AsImentioned,Linuxmakesyourcomputeratruemultiusersystem,thatmeansthat besidesroot,youcanandshouldworkasanotherperson.Isay'should'becausedoing routineworkas'root'couldbehazardoustoyourhealth.WhenIfirststartedusing Linuxmyself,informationwasnotallthatreadilyavailableandIstillhadthat'one computeroneuser'conceptinmybrain.ItwasafterIhadtrashedallofthefilesand programsthatmakeLinuxrunthatIrealizedthatcarethatworkingregularlyasroot wasn'tagoodidea.

Working as another user


Well,thenhowdoyoudoyourdaytodayworkwithLinux?Easy,workingasauser otherthanroot.Youmaypickthenameyoulike.Tryyourname.Ifyournameis "Bob"thenyoucouldcreateauseraccountfor'bob'.Bytheway,ifPrinceCharlesis readingthis,CharlesPhilipArthurGeorgeisabittoolongandhasspaces,which Linuxdoesn'tlikeheshouldtry'charlie'.OnethingIfindEXTREMELYhelpfulis thatwithLinux,Icanworkasdifferentpeople.ItshouldnotbeinferredherethatI havesplitpersonalitydisorder.Iamjustaguywithacoupleofdifferentjobs.This wayIcanorganizemyworkalotbetterandbackupsareeasierthiswaytoo.

21

Adding a new user


Well,Bob,nowit'stimetocreateyouraccount.IfyournameisHrothgar,substitute 'bob'for'Hrothgar'or'Hrothie'fortheremainderofthelesson. Now'root'hastodothisstuff.Yes,IknowIjustwarnedyouaboutworkingasroot, butthisiswhereyouhavetoexertyourauthority.Mostmajordistributionshavetools todothis.SuSE,forexample,hasanicetoolcalledYASTwhichletsyouaddusers painlessly.Youjustfillinthecorrectinformation.ConsultyourLinuxversionfor informationontheirtools.Thereisalsothegetyourhandsdirtywayofdoingthis. Actuallyyouwon'tgetyourhandsdirtyunlessyou'reeatingbarbecuedribsatthe sametime.

Using 'useradd' and 'passwd'


Toaddanewuser,youcanalsousethecommand'useradd'.Kindofalogicalname, isn'tit? Trythis:useradd bob.Youprobablywon'tseeanyfireworksgooff.Youmightnot seeanything.Thatdoesn'tmatter.Linuxhasbeentoldthatthere'sanewuserandhis name's'bob'. Nowyoushouldgiveyourselfapassword. Dothis:passwd bob. Linuxwillaskyouforyourpassword.FollowthesameadviceIgavepreviously aboutpasswords.Also,don'tuseyour'root'password.Like'oneman,onevote'it's 'oneuseronepassword'Youwillbeaskedtorepeatit.

Virtual Terminals
OneofthecoolestthingsthatLinuxhastoofferistheconceptofvirtualterminals. BackinthedaysofMSDOS,oneprogramcouldonlyberunbyoneuseratatime. LinuxinnongraphicsmodemayresembleMSDOSsomewhat,butthat'swherethe similaritiesend.Linuxisatruemultitasking,multiusersystem.UnlikeMSDOS, youcancanworkasmorethanoneuserwithmorethanoneprogramatatime.

The ALT-F keys


Let'ssay,ifyouwereworkingasauser,'bob'forexample,andyoufoundthatyou neededtodosomethingas'root'.Youwouldn'thavetoshutdowntheprogramyou wereworkingwith.YoucouldjustpressALTF2andLinuxwillpromptyoutologin asadifferentuser,inthiscase,'root'.You'djusttypetherootpasswordandthenyou candostuffas'root'.Prettycool,wouldn'tyousay? 22

ThecombinationofALT,plustheFkeyswillallowyoutologinasadifferentuser, orasthesameuser,buttorunadifferentprogram.Allyouthenneedtodoistype: 'exit'whenyourfinished,andthenpressALTF1againtogetbacktoyouroriginal terminal.

A preview of virtual terminals in X-window


It'struethatthe1990'sbroughtustheeraofthegraphicuserinterface,popularizedby Macintosh OSes and Microsoft Windows. This gave us the opportunity to have variousprogramsrunningatthesametime.TheXwindowsystemofLinuxwilllet youdothisaswell,butthenwecanaddtheconceptofmultiusertoit. Ifyou'vebeenexperimentingwithyourwindowsmanageralready,youmightwantto tryonemorething.ThecombinationCRLALTF6willgetyououtofyourwindows managermomentarilysoyoucanloginasadifferentuser.PressingALTF7willget youbacktoyourwindowsmanageragain.We'llmentionthisagaininthelessonon Xwindow.

23

Lesson Four
Creating your 'routine' in Linux
What's in your user directory
Whenyoucreateanewuser,thereisadirectorycreatedforthatuserin/home.Tosee what'sinthisnewdirectory,youhavetodothefollowing. Gotothe/homedirectory.typing: cd /home youcanmakesureyou'reinthe/homedirectorybytyping'pwd'You'llseethis: /home. Nowyouneedtotype:
cd bob

MSDOSuserswillbefamiliarwiththatone. Youcantype: ls -a toseewhat'sinthedirectory.We'llgointomoredetailwiththelscommandlater. Withtheaoption,you'llseesomefilesthatbeginwitha'.'(period/dot).Thosewould normallybehiddenfromyouifyoudidn'tusethea. Nowyoucangotoworkas'bob',or'hrothgar'orwhoeveryouhappentobe.

Shells in Linux
The Linux shell
Whenyou'rerunningLinuxandstarttotypethingsonthatblackscreen,youareusing ashell.Anyoperatingsystemusesashelltogetcommandsfromthekeyboardtothe computer.It'saloteasierthanpunchingholesincardsliketheyusedtodointheold days.ThereareactuallyprogramsforLinuxwhereyoutalkthroughamicrophoneand Linuxwillcarryoutcommandsthatyou'veprogrammedinadvance.It'sreallycool. Fornow,thoughwe'llconcentrateonthekeyboard.

24

ThemostpopularshellusedforLinuxisthebashshell.bashmeans"BourneAgain Shell".ItisafreeversionoftheBourneshellandusesalittleplayonwords,asyou cansee.Ourlessonwilldealwiththatone.Therearealso:csh,ksh,tcsh,zsh...

Why you need to use a shell


Themostcommoncommandsacomputerreceivesareonestocopyfiles,movefiles around,listfilesanddeletefiles.Popularoperatingsystemshaveperfectedthisto suchadegreethattheyhavegraphicinterfaceprogramstodoallthisforyoujustby movingthemousearoundandclickingonafewbuttons.Linuxhastheseprograms too,butanybodywho'sseriouslythinkingofusingLinuxonadaytodaybasicshould befamiliarwiththecommandsthatyoutypeinbyhand.Somepeopleseethisasa throwbacktotheolddays.Iseeitasawaytohavemorepoweroveryourcomputer because even those operating systems that are billed as more 'user friendly' have providedyouwithashell,justincaseyouneedit.Andsometimesyoudo!

The Linux file system


Now'sthetimetolearnalittlebitabouttheLinuxfilesystem.We'lllearnaboutwhere Linuxputsitstuff,wheretofindstuffandalittlebitaboutwhatthatstuffis.

Getting in and out of directories with 'cd'


Wesawafewcommandsinthelastlesson,butwedidn'tgointothemmuch.Wewill handlealotofcommandsinmoredetaillaterlessons.Thislessonwillcoverthose commandswhichyouwillneedtoseewhat'sunderLinux'shood. Thefirstoneweshouldlookatis'cd'.AgainMSDOSuserswillbefamiliarwiththis. cdwillgetyouinandoutofdirectories. Trythisone:
cd /

Thiswillgetyouintothe'root'ormaindirectory.It'sthedirectoryofdirectories,the kingofkings,yourshowofshows.Therootdirectoryshouldn'tbeconfusedwith root'sdirectory.Thatis/root.

The basic directory structure in Linux


Nowtypethis:
ls

Youwillprobablyseesomethinglikethis: cdrom home opt tmp dev bin 25 lib etc proc lost+found usr root var

boot floppy mnt sbin Theywillbeblueincolor.Thosearedirectories.

The /bin directory


Nowtypethis:
cd bin Typelsagain.

This is the famous bin/ directory. You know, I have always felt this one was misnamed.Likewhenpeoplesay,'That'snogood,throwitinthebin'Actually,bin/is one of the most important directories in Linux. You'll find all of the most used commandsthere.Rightnowyoushouldbeseeingalotofred(orgreen,dependingon yourversionofLinux).Thoseareprograms.

The /etc directory


Nowletslookatanotherdirectory.There'salongwayandashortcut.Firstthelong way. 'cd..'willgetyououtofbin/. 'cdetc'willgetyouintotheetc/directory. oryoucanjusttype'cd/etc'inthebin/directoryanditwillbringyoutotheetc/ directory. Anyway,youarenowintheetc/directory.Thishousesmostoftheconfigurationfiles forLinux.lilo.conf,thefilethattellsyouwhichOStobootisinthere. you'llsee:lilo.conf Andyoudon'tevenhavetotypethewholething.Youcouldjusttype'lsli'andpush thetabkey.Linuxwilltypetherestforyou.Isn'tthatcool!

Some more cool shortcuts


Trythisone:type ls m pushthetabkey.Linuxisgoingtobeepacoupleof times,butyoukeeppushing.Youwillnowseeeveryfileinthedirectorythatbegins withtheletter'm'. Nowaddan'o'onto ls m soyouget ls mo nowpushthetabkey.You shouldsee'motd'.Thisisafilethatcontainsyourstartupmessage.SuSEhasafamous onethatsays'Havealotoffun!'.IlikethatonesoIhaven'tchangedit,butyoucan changeitsothatLinuxsaysanythingyouwantwhenyoulogin. Do youwantto make surethat lilo.conf is stillinthere?Youdon't havetotype 'lilo.conf'orevenpartofitandpressthetabkeyanymore.Youjusthavetopressthe uparrow.Yourlastcommandswillappearwhenyoudothat.

26

Yourcommandsaresavedinahistoryfilelocatedinyourhomedirectory.Themore timesyoupresstheupbutton,thefartherbackintimeyougo.Pressingthedown buttongetsyoubacktoyourmostrecentcommands.Juststoponthecommandyou wantandpress'enter'.Youcaneventypethecommand history andallofthe last400orsocommandsyou'vetypedwillbepresented.Asyougetmoreproficientin Linux,you'llwillfindthatthis really comesinhandy.Youcanoftenfindoutthe answertothequestion:HowdidIdothat?byconsultingyourshellhistory.

The /usr directory


Let'stalkaboutusingsomeoptionswithcommands. Forexample,typing: ls -l contentsofadirectory. willgiveyoumoredetailedinformationaboutthe

Trythis:Firstlet'sgototheusr/directorybydoing cd /usr thentype: ls -l .Youwillseemoreinformation,likedates,somenumbers,lettercombinations, it'llsay'root'alot.We'llgetintomoredetailaboutwhatallofthatmeanslaterinthe course.You'llseemainlysubdirectorieshere.Theusr/directorycontainsfilesand programsmeanttobeusedbyalloftheusersonthesystem.

In Linux, everything is a file


Yes,notonlyisthatdigitalphotoofTheEiffelTowerafilebutyourmonitorisafile too!Howcanthatbe?Let'strytoexplainit.

The /dev directory


Ifyoudocd /devandthenls,you'llseealotofyellowoutlinedinblack.Theseare thedevicesthatyoursystemusesorcanuse.EverythingisconsideredafileinLinux, soyourharddiskiskepttrackofasafilethatsitsthere.Ifyou'reusinganIDEhard drive(asopposedtoSCSI),yourharddrivewillbeknownas/dev/hda.Don'tdelete that,becauseyourharddiskwillspinaround,comejumpingoutofyourcomputer, land on the floor and spill out ooze all over the place. No, not really. You will probablynothavetolookin/devverymuch,sodon'tworryaboutthat.

The /boot directory


Doing:cd /bootwillgetyouintothe/bootdirectory.Youwillnotfindanybootsor shoesorfootwearofanykindthere.That'swheretheLinuxkernelusuallyis.Power usersmaychangethelocationofthekernelforreasonsoftheirown(theymayprefer/ shoe),butitisnormallyplacedthereonmostsystems.Youwilleventuallyhaveto usethisdirectory,becauseyoumayneedtousetwoormoredifferenttypesofkernels inthefuture.Thatwillbetakenupinamoreadvancedlesson.

27

root's directory - /root


Ifyouarenotworkingas'root'andyoutype cd /root,youwillbetakentothe directory/root.However,youwon'tbeabletodoanythingwhileyou'rethere.Root's homedirectoryisarestrictedareaforeverybodyelse.Linuxresponseissortoflike, 'Youdon'thavetoknowthat'.Users'homedirectoriesareundercertainrestrictionsfor otherusersaswell.

The /sbin directory


/sbinisanotheroneofthoseofflimitsdirectories.Youmaylook,butyoucan'ttouch. Thisdirectoryislike/bininthatithasfrequentlyusedprogramsinit,butthey'reonly meanttobeusedbyroot.'Shutdown'isinthere.Onlyrootcanshutdownthesystem. Ifauserotherthanroottriedtoshutdownthesystem,heorshewouldgetamessage sayingthatonlyrootcandothat.Thenthatpersonwouldbefollowedbythesecret policeforthreemonths.

The /tmp directory


/tmpisadirectorythatisusedtostoretemporaryfiles,asthenamemaysuggest.You willfindlateronthatwhenyouuseaWindowsstylesystemwithLinuxlikeKDE, thiswindowmanagerwillcreatefilestherefortemporaryuse.Whenyoudoubleclick onaniconofaphoto,thephotocomesupforyoutoseebutatemporaryfileis createdwhileyou'relookingatthephoto.Thetemporaryfileisdeletedwhenyou closetheKDEimageprogram.It'smainlytheprogramsthatworkunderawindows managerthattakeadvantageofthisdirectory.

The /var directory


/varisadirectoryforcertainfilesthatmaychangetheirsize(ie.variablesize)For example, there are a few excellent databases for Linux. One is called MySQL. Normally,MySQLkeepsitsdatainasubdirectoryof/varcalled/var/mysql/.IfIhad anecommercewebsite,Iwouldhaveadatabasetoregisterpurchases.Thatdatabase wouldobviouslygrowinsize.Andifitdidn'tthenI'dbeintrouble.Itisalsothe normalplacewhereemailserversstoretheirincomingmail.Again,emailvariesin sizeaswell.

The /lib directory


/lib isforlibraryfiles,that'swherethename/libcomesfrom.Programsmayuse librariestocarryouttheirfunctions.Differentprogramsusethesamelibraries,so Linuxwillstorethemheresothateveryprogramknowswheretofindthem.Youwill probably not have to worry about this directory much unless you start getting messageslike'can'tfindsharedlibrary...'.Thatwillsometimeshappenswhenyou've downloadedsomeprogramandhadtocompileityourselffromsourceandeven 28

then, getting what are known as "dependency" problems are quite rare. Most programs,evenwhencompiledfromsource,usuallyhaveapreconfigurationprogram thatmakesuretheycanfindwhatlibrariesthey"depend"ontorun.Iftheydon't, they'lltellyouyoucan'tinstalltheprogram.

Home Sweet Home


Wetalkedabout/homebefore.Thisadirectoryforstoringusers'personalfiles.Allof us have certain preferences for using programs. These preferences are usually includedinconfigurationfileswhicharealsostoredinusers'homedirectories.Most ofthesefilesstartwitha'.'(period/dot). Ifyougotoyourhomedirectory,'cd/home/[username]'andtype:
ls -a

youwillseethesefiles.

The /floppy, /cdrom and /mnt directories


MostinstallationsofLinuxwillalsoprovidethesedirectories: /mnt /cdrom /floppy Theseshouldn'tcontainanything.Lateron,we'llexplaininmoredetailwhattheseare for.Let'sjustsaythatinLinux,ifyouwanttoseewhat'sonafloppydiskoraCD, you'renotgoingtobeabletojustclickonan'a:'iconora'd:'icon.You'regoingtodo cd /floppy orcd /cdrom. Ifyoutrythatnowyouprobablywon'tseeanything.AsIsaid,morethesedirectories laterinthecourse. Well,we'velookedunderLinux'shood,sotospeak.Inthenextlesson,we'lltakeher foralittlespin.

29

Lesson Five
Day to day with Linux
Shutting down Linux
AtthispointyoushouldhaveinstalledLinux,andyou'velookedaroundatwhatyou have.Andthenwhenyou'refinishedyou'llhavetoshutoffyourcomputer. Actually,therearecomputersthatarenevershutoff.ImagineifyourISPshutoffthe computereverynight!TheInternetisa24/7businesssothatwouldn'tbepractical. Therearealsopeoplewhoprobablyjustshutofftheirmonitor.Asyouprobablyget somesleepoccasionally,soweshouldmaybeletourmachinehavearesttooonceand awhile.Forthis,we'llusetheshutdowncommand.

The importance of the 'shutdown' command


Asanyone who'sused acomputer knows,if youshutoffyou'recomputerbefore you'vefinishedsavingwork,orifthere'sapoweroutagethatshutsitoffforyou,data willbelost.Atfirst,ifyoushutoffLinuxincorrectlyortherewasaninopportune thunderstormandyoulostelectricalpower,youcoulddoseveredamagetoyour Linuxfilesystem.Thatwillveryrarelyhappenthesedays,butyoushouldalwaysuse theshutdowncommandwhenyouwanttoshutoffyourcomputer.Linuxwilltellyou aboutitifyoudon'titwillrunacheckonyourharddiskautomaticallywhenyouuse it again. Ifyouhaveabigharddisk,youmightaswell goandmakeyourself a sandwichbecauseit'sgoingtotakeawhile.Linuxwillalsorunaroutinecheckevery once and a while automatically. You also have our permission to fix yourself a sandwichinthesecasestoo.

Shutdown for a single computer


ThemostcommonwayofshuttingdownasingleuserLinuxsystemisforyouasroot toissuethecommand:
shutdown -h now

Youusethiswhenyouplanonshuttingyourcomputeroffatthatmoment,asopposed tosomelatertime. You'llseeamessagelike:


Linux is going for system halt NOW

30

Itwillstarttoshutoffprogramsthatyou'recomputerisusingandyou'llseeitall happening.That'sbecauseLinuxisatransparentsystem.Itletsyouseeeverythingit's doing.Itwon'tgiveyouasimplemessagetellingyoutowaitandthenanotherone tellingyouyoucanshutitoffnow.Ifsomethingiscausingaproblem,itwilltellyou aboutitwhenitstartsupandwhenitshutsdown.Thatway,ifyouarehavinga problem,youmaybeabletotrackitdown.Ifyoudon'tknowhowtosolveit,youcan tellanotherpersonwhatyousawandheorshemaybeabletohelpyou. Withthe or


Power down shutdown -h now System halted

command,youmustwaituntilyouseethemessage:

beforeyoushutoffthecomputer.

Re-booting the computer


Theothercommandthatyouwillprobablyuseis:
shutdown -r now

Ifyou haveinstalledadualbootsystemandyouwanttousetheotheroperating system,(whywouldyouwanttodothat?)youwouldusethiscommand.Youwillget asimilarmessageaswiththeh(halt)optionthatwillsaysomethinglike:


System going for reboot NOW

ThebasicreasonbehindallofthesemessagesisthatLinuxwasconceivedtobea networkedoperatingsystem.Youhavepeopleatworkstationsonthenetworkbusily doingtheirwork.Thelastpartoftheshutdowncommandnowisfineforasingleuser homePC,butonanetworksystemthiswouldbechangedtoindicateatime.Thatway peoplewouldhaveachancetofinishwhattheyweredoingbeforethesystemwent downformaintenence.Using'now',inanetwork,wouldprobablybehazardoustothe healthofthepersonwhosentthatcommand. The nexttimeyoushutdownyoursystem,youmaywanttotry using sometime optionsinsteadofjust now.Forexample,youmaywanttotryshuttingdownthe computeratagiventime.
shutdown -h 20:01

Whichwillshutdownthecomputerat8:01PM.Youcouldalsotry:
shutdown -h +5

Thatshutsdownthecomputerin5minutestime. NowyouknowthecorrectwaytoshutdownyourLinuxsystem.Inthenextlesson we'lltalkusingthesystemagain.

Text editors in Linux


IfIweretochooseoneofthemainreasonwhypeopleusePCs,Iwoulddefinitelysay forwriting.Withacomputerandawordprocessingprogram,crossouts,whiteout 31

andcrumpleduppaperhasdisappearedforever.AllthoseoldSmithCoronasgotput away. Linuxisjustaswellsuitedforwordprocessingasanyotheroperatingsystem.There areseveralexcellentwordprocessingprogramsforLinuxlikeAbiWord,KWord,part oftheKOfficesuiteandtheOpenOffice.orgsuite'swordprocessor.We'lltalkabout thesekindsofprogramsinalaterlesson.First,weshouldtalkabouttheterminal modetexteditorsthatareavailableforLinux.

Why use a text editor?


Atexteditorisjustlikeawordprocessorwithoutalotoffeatures.Alloperating systemscomewithabasictexteditor.Linuxcomeswithseveral.Themainuseofa texteditorisforwritingsomethinginplaintextwithnoformattingsothatanother programcanreadit.Basedontheinformationitgetsfromthatfile,theprogramwill runonewayoranother.

The text editor vi


ThemostpopulartexteditorforLinuxiscalled'vi'.Thisisaprogramthatcomesfrom UNIX.Thereisamorerecentversioncalled'vim'whichmeans'viimproved'.The problemwith'vi'or'vim'isthatalotofpeopledon'tlikeit.Youhavetoremembera lotofkeycombinationstodostuffthatothertexteditorswilldoforyoumoreeasily. Weshouldgothroughsomebasic'vi'commands,becauseIhavefoundthat'vi'is goodifIwanttogetintoatextfilequicklyandchangesomethingorIwanttowritea shortnotetomyself.Igenerallydonotuse"vi"foranythingthatrequiresmorethan about30secondsofwork,buttherearepeoplewhoswearby'vi'anddoallkindsof thingswithitlikedesigningentirewebsites.

Working with 'vi'


Let'smakeatextfile.Type:
vi tryvi

You'llseealineoftildesdowntheleftsideandthename'tryvi'atthebottomand [newfile]. Towritesomething,youhavetopressESCandthe'i'key(iforinsert).Evenifyou don'tpress'ESCi'itusuallygetstheideathatyouwanttotypesomethingandlets youdoitafterafewkeystrokes.Youshouldgetusedtothe'ESCi'keyssoyoudon't endupwriting'arJohn'insteadof'DearJohn'. PressESC+'i'thentype: hello vi

32

IfyouwrotejelloviorjellobiorsomethingIdon'twanttoknowabout,youcan alwayseraseyourmistakeswiththebackspacekey. Tosavethisfile,youwouldpressESCthenthecolonkey':'then'w'(write) Tosavethefileandquitvi,youwouldpressESC,ESCthecolonkey':'thenwq (write,quit) Toquitwithoutsaving,press ESC,':'then'q'.Vimayprotestifyou'vewritten somethingandyoudon'twanttosaveit.IfyoupressESC':''q!'withanexclamation point,viwillacceptitandnotsaveyourchanges. That'sviinanutshell,ormorelikeasesameseed.Therearealotofcommandsinvi andyoumayexplorethoseonyourownatalaterdate,onyourowntermsandinthe privacyofyourownhome.

'pico' and 'joe'


'pico'and'joe'soundslikeacomicstrip.Actually,theyaretwoothertexteditorsthat IlikeandIthinkarealittleeasiertomanage.They'relike'vi'inthatyouusethemto createandeditnonformattedtext,butthey'realittlemoreuserfriendly.Using'joe' 'joe'wascreatedbyJosephAllen,sothat'swhyit'scalledJoe.Isupposeifhisname hadbeenHrothgarAllen,itwouldhavebeencalled'hroth'. Touse'joe',youcouldtype: joe tryjoe You won't see the tildes like vi. It looks a little friendlier. The majority of joe's commandsarebasedonthe CTRLK keysandathirdkey.Themostimportantof theseisCTRLKHwhichgetsyou'help'.Helpshowsyouthekeycombinationsto usewith'joe'. Themost importantthingabout 'joe' isthelogicalconceptthatyoucanjuststart writingifyouwant.Trywritinganythingyouwant. Tosaveit,pressCTRLKD.Tosaveandquit,CTRLKX. Toquitwithoutsaving,CTRLC,(withouttheK). Ifyouwanttoseetheotherfeaturesof'joe',pressCTRLKH,asImentionedbefore. Myfavoritelittleaddedfeatureof'joe'isthatifyoueditafileagain,itwillsavethe previousfilewithatildeontheend,like'tryjoe~'Thatlittletildefilehassavedmy lifeacoupleoftimes.(well,maybenotmylife)Butithassavedmealotofwork.I've madesomechangestoafileandthenfoundoutthatwasn'tagoodidea.Icould alwaysfallbackonthetildefile,whichisacopyofyourpreviousedit. 33

'joe'isaverygoodoptionforwritingthoseshorttextfilesthatyou'llneed.

Using 'pico'
'pico'isanotherfriendlytexteditor.Ifyoutype: pico trypico You'llseethecommandsyouneedin'pico'specifiedatthebottom.Youcanjuststart writinganythingyouwant. Tosavethefile,pressCTRLo.Tosaveandquitortojustquit,pressCTRLx Picowillalwaysaskyouifyouwanttodowhatyou'redoing.That'sgood.Questions likethatwillkeepyoufromsendingafileintononexistencewithoutwantingto.All theothercommandsyou'llneedareatthebottomofthepage. Well,thisisourlittleoverviewofthemaintexteditorsavailableforLinux.Inour nextlesson,we'regoingtoneedtouseoneinordertomakeourworkinLinuxalittle bitsaferandeasier.

Vi for budding power users


Again,myaimisnottodointoatreatiseonvi,buthereareafewmorecommands thatyoumightneedtodoalittlemoreheavylifting.

Removing Lines
Youmayfindthatyouneedtoremoveanentirelinefromafile.Justplacethecursor atthebeginningofthelineandtype: ESC+d (dfordelete) Changingyourmind Sometimesyouwishyouhadn'tdonesomething.Withvi,youcanundowhatyoujust did. ESC+u (uforundo) Changingyourmind(again) Again,youhavesecondthoughts.Withvi,therearenoregrets. ESC+q! (q!forquitandI*really*meanit!) 34

The exclamation point (!) is used in vi to override default settings. If you make changestoafile,viisgoingtoaskyouifyouwanttosavethem.'q!'meansthatyou wanttoquitwithoutsaving.

Where did I put that word?


Didyoumisplaceawordinyourfile.Youcanfinditeasilywithvi ESC+/[word] (slashforumm..slash,Iguess.) Ifyou'relooking forthewordnonplussedinyourtext(asin:'viissoeasyIam nonplussed')youwouldtype: ESC/nonplussed anditwillfindeveryinstanceofthewordnonplussed.

Can I change that word?


Maybeyoudon'twanttousethewordnonplussed.Perhapsit'sbettertouseamore wellknownword.Youcanusevitochangetheword.Firstyoucouldusethe /nonplussed tolookforthatword.Whenyoufindit,youwouldthentype ESC:s/nonplussed/amazed/ toreplacethewordonthatline. Ifyouweresurethatyouwantedtoreplaceallinstancesofthatwordinthewhole text,youcouldtypethis ESC:%s/nonplussed/amazed/g andnonplussedwouldbechangedtoamazedthroughoutthetext. Ifyouwanttogetsomecontroloverwhatyoureplacethatisyouwanttousedboth nonplussedandamazed,thenyouwouldaddgctotheend: ESC:%s/nonplussed/amazed/gc Viwillnowaskyouforconfirmation.

Vi configuration settings
Therearesomebasicviconfigurationsettingthatyoushouldbeawareofifyouwant tousethistexteditorcomfortably. WordWrapping Ifyoudon'twantyourwordsrunningoffthepageintooblivion,youcansettheword wrappingfeatureinvi ESC:setwm=30

35

Thisisagoodwrapformepersonally.Itsetsthewrapto30spacesfromtherightsoit makesittight.Thismeansthatthebiggerthenumber,thesooneryougetalinebreak. Ifyousendsomethingviaemail,thenthistightwrapensuresthatitwillgetthere withoutthelinesbeingbrokenintostairsteps. Viasanemaileditor Whatdidyousay?Viandemail?Yes!Youcanuseviasanemaileditor.Thisismost commonlydonewiththeemailclientmutt MoreVi Thisjustscratchesthesurfaceofwhatyoucandowithvi.HereI'vetriedtoshowyou whatmightbethemostusefulfeaturesandsettingofvi.Itshouldbeenoughtoget somebasicworkdonewiththisubiquitouseditorforLinux.

Moreinfo: http://howto.linux.org.ba/howto/vi.htm

36

Lesson Six
Frequently Used Shell Commands
IfyouinstallawindowmanagerlikeKDE,youcancopy,delete,moveandrename filesbywayofagraphicuserinterfacelikeKonqueror.ButasImentionedbefore, shellcommandsareprettystandardinLinux,sowe'regoingtoteachyoutheonesthat you'remostlikelytouse.Youcanusethembothintextmodeorinyourxterminal whenyou'reingraphicsmode.

The 'cd' command


Thefirstcommandyou'lluseis'cd'.Wetalkedaboutthisinapreviouslesson,solet's reviewthebasics. 'cd'means'changedirectory'. Typing:cd/[directoryname]willgetyouintooneofthemaindirectoriesinLinux. Typingcd..willgetyououtofit. Typingcdwithoutthe/andasubdirectorynamewillgetintothatsubdirectory. Remember,youdon'thavetotypethewholename.Typing:'cd'andthefirstletteror lettersofadirectoryandtheTABkeywillcompleteitforyou.Thenallyouhaveto doispressenter. Ifyoutypejust:'cd'you'llgobacktoyourhomedirectory

The 'ls' command


Toshowthestudentthevariousvariationsofthe'ls'command'ls'isanothercommand thatwe'vediscussedabitbefore.Let'sgointosomemoredetail. Typing'ls'willlistthecontentsofadirectorywithjustinformationaboutfilenames. Youcanuse'lsa*'tolistthenamesofallthefilesthatbeginwiththeletter'a'andso ondownthroughthealphabet.Pleasedonotusethecuneiformalphabetunlessyou're fromancientMesopotamia.

37

Normallywe'llwanttoaddonsomeparameters(those[letter]combinations)sothat we'llgetsomemoredetail.

Using 'ls -l'


Toshowthestudenthowtogetsomemoredetailwith'lsl''lsl'willgetyoua detailedlistingofthedirectorylikethis. rwrr 1 bob users 103824 Jul1012:01 waikiki.jpg

Thefirstpart,thoseletter,arefilepermissions.We'llgointothatinalaterlesson. Thatbasicallyshowswhatyouandothersareallowedtodowiththefile,likereadit, modifyitormakenastycommentsaboutit. Thenextoneshowsthatyou'vegot1file.Thenextonethatitbelongstoyou,'bob'. ThenextonerepresentsthatLinux,notonlyrecognizesusers,butalsogroupsof users.We'llgointothatinthenextcourse.Thenumbersarethesizeofthefilein bytes.Youhavethedateandwhenitwascreatedormodifiedorcopiedthere.Lastly, youhavethenameofthefile,waikiki.jpg,whichisobviouslyyourimportanttax records. 'lsl'willgiveyouadetailedlistinginalphabeticalorder,startingwithanyfilethat beginswithanumber,thenanyfilethatbeginswithacapitalletterandthenany normalfilethatbeginswithalowercaseletter.Soifyouhaveafile'007_secrets.txt' that'llbethefirstoneyousee.

Other parameters with 'ls'


Nowlet'saddsomemoreparameterson. 'lslt'willgiveyoualistingaccordingtothetimewiththenewestonesappearing firstinthelist.Youdon'tneedtoseparatetheparameterseither.'lslt'and'lslt'are thesamething.Ifyouwanttheoldesttoappearfirst,try: ls -ltr The'r'isforreverseorder. Thereareacoupleofparametersincapitalsthatyoumaywanttouse.'lslS'willlist yourfilesfrombiggesttosmallest.'lslSr'willreversethisorder. 'lslX'willlistfilesaccordingtotypeinalphabeticalorder.Ifyouhaveanythatend in*.zip,thenthosewillbelast.Ifyouwantthosetobefirst,nowyouknow:'lslXr' Thereisalsoaparameterthatwillhelpyouifyouwanttofindoutmoreaboutthese commandsoranyothers.'lshelp'willgiveyoudetailsofallthepossiblevariations forthiscommand.

38

The 'file' command


Fileisaninterestinglittlecommand.MSDOSgotusallusedtotheideathatafile hadtohaveanextension(file.extensionlike'novel.txt')thattolduswhatkindofa fileitwas.InLinux,it's50/50.Youdon'thavetodothatifyoudon'twant.InMS DOS,programsendin'.exe',inLinux,theydon'thavetoandprobablywon't. Linuxisalsocolorcoded,asyouknow,soonceyougetusedtothecolors,you'll know what the file is about. Let's say your friend Tony, the one with the magic markers,sendsyouafilehesaysisreallyneat.It'sattachedtoanemailmessageand itsays'stuff'.Youcanseewhattypeoffileitisbytyping: file stuff Youmayseesomethinglikethis: stuff: ASCII text Thismeansthatthefilecontainsplaintext.It'sprobablysomejokesorhisfavorite chilirecipe. Ifyoudon'tknowwhatsomeparticularfilecontainsandyou'recuriousaboutit,you canusethiscommandtogetsomeinformationaboutthefile.

'more' and 'less'


Tointroducethestudenttothesecommands'more'isacommandthatyoucanuseto read,forexample,what'swritteninthat'stuff'filethatTonysentyou. Youwouldtype'morestuff'toseethejokes.Pressthe'q'keytostopviewingthefile It'susefulforthis,butnotreallyideal.We'lltalkmoreabout'more'inthislesson whenweuseitincombinationwithothercommands 'less'isbetterforviewingfiles.Youcanscrollbackuptoseethewholetextifyou want.Youcan'tdothatwith'more'.'less'ismorethan'more',ifyougetmymeaning. Type less stuff toseeTony'sjokesagain.Again,pressthe'q'keytostopviewingthefile.

The 'cp' command


ToshowyouhowtocopyfileswithLinuxWetalkedabout'cp'inthelessonon aliases.'cp'isforcopyingfilesfromoneplacetoanother,orformakingaduplicateof onefileunderadifferentname. Let'sgobacktoTony's'stuff'file.Forexample,ifyousavedTony'semailattachment toyourmain/homedirectory,/home/[yourname],youmaywanttocreateadirectory

39

tokeepTony'sfilesYoucouldmakethedirectoryforTonytonyd(Tony'slastnameis Dweebweiler) mkdir tonyd thenyoucando: cp stuff tonyd RememberuseyourTABkeytosavetime. Nowyou'regoingtohaveTWOfilesnamed'stuff'becauseyoucopiedthatfiletothe directory'tonyd/'youdidn'tmoveitthere.You'llhavetheoriginal'stuff'inyour homedirectoryandthenthecopyin/home/[yourname]/tonyd/. You'llbeabletotellthedifferencebetweenthetwofilesbecausethecopyof'stuff'in thedirectory'tonyd'willshowadifferenttime.Ifyouusethecommandlslstuffon bothfiles,you'llseethis. Ifyouhadusedthecommand cpp insteadofjust cp youwouldendupwithtwo identicalfilesintwodifferentplaces.Ifyoudon'twantthat,there'sabetterwayof doingitsothat'stuff'isonlyinthedirectory'tonyd'.That'sthemvcommand.We'll talkaboutthatshortly.

More uses of the 'cp' command


Toshowyouhowtocopydirectoriesandcreateduplicatesoffiles.Nowlet'stalk abouttwomorebasicusesofthecpcommandandsomeshortcuts. Youcanalsocopyentiredirectoriestoanotherplace.AsImentionedinaprevious lesson,youmaywanttoworkastwodifferentusersfortwodifferentjobs.Youmay beworkingas'fred'andyourdirectory'tonyd'isinthedirectory/home/bob,where youworkas'bob' As'fred',youcanusethecommand: cp -r /home/bob/tonyd/ /home/fred/ Ifyou'reinyourhomedirectoryyoucanusethiscommand cp -r /home/bob/tonyd/ ./ tocopythedirectory'tonyd'toyourhomedirectory. Youmayalsousethecommand cp -r /home/bob/tonyd/ ~ with the tilde wherever you happen to be and that will automatically copy the directory'tonyd'toyourotherhomedirectory. Theotheruseof'cp'wetalkedaboutwastogetacopyofafilewithadifferentname. Forexample,Tony'sfile'stuff'isloadedwithjokes.Youmaywanttoaddsomemore jokesandthenpassitalongtoanotherpersonYoucoulddothis: cp stuff stuff2 orchooseanamethat'smeaningfulforyouotherthan'stuff2'. 40

Nowyouhaveanotherfilethatyoucanaddjokestowhileyoupreservetheoriginal file.Youcanopenitin'pico'andstartwriting:"Whydidthechickencrosstheroad..." AlwaysremembertousethatTABkeyandtheupanddownarrowstosaveyourself sometime. Nowwe'lllookatthecommand'mv'.

The 'mv' command


'mv'isacommandthatwe'regoingtousetomovefilesaroundortorenamethem. 'mv'sortofhasasplitpersonalitybecauseitservesthesetwofunctionsatthesame time.

'mv' command for renaming files


Let'sgobackyetagaintoTony'sfile,'stuff'again.'stuff'isnotagoodnameforafile justas'book'isn'tagoodnameforabook.Justimagine:"Thenumberonebestselling bookthisweekis'Book'byJohnAuthor. You should probably rename this file to something meaningful. I would suggest doingsomethinglikethis: mv stuff tonys_jokes Youmayhavenoticedtheunderscore'_'inthetitle.It'stherebecauseLinuxdoesn't reallylikespacesinthefilenames.YoucandoitandLinuxwillacceptitbutitwill puta\\betweenthedifferentwords.Spacesaresortof'fauxpas'inLinuxbutnot 'verboten'.Itwouldbetoyouradvantagetouse'_'betweenwordsthough.

Moving files with the 'mv' command


Nowyoucanusethe'mv'commandtomoveTony'sjokesintothedirectoryyoumade tokeephisfiles. mv tonys_jokes tonyd/ Ifyoudocdtonydandthenlsto*youwillseehisfiletherealongwith'toms_jokes' and 'tomato_soup_recipe' (ifyou haveanotherfriendnamedTomandyouliketo cook). Youcanalsomoveentiredirectorieswiththiscommand.Youdonothavetousethe 'r'optionasyoudidwith'cp'.Youwouldjustsubstitutethefilenameforadirectory name mv tonyd/ my_friends/ wouldmovethedirectory'tonyd'tothedirectory'my_friends'. What?Youdon'thavethedirectory'my_friends'?Well,let'screateitwithanother command. 41

The 'mkdir' command


'mkdir'isthecommandformakingdirectories.'mkdir'maybefamiliartoMSDOS usersoutthere.Asyouhavenoticed,thepeoplewhowrotetheseprogramstriedto give them names that described what they do more or less, not as long as 'makemeadirectoryplease'andnottoocrypticlike'xr77b'.

Using the 'mkdir' command


Tocreatethedirectory'my_friends'thatwetalkedaboutinthelastlesson,youwould type: mkdir my_friends Therearenowhistlesorbuzzers.Ifyou'dlikesomesortofacknowledgment,you couldtype mkdir --verbose my_friends anditwilltellyouthatyoucreatedthedirectory. IfyoutypelslYou'llseeittherealongwithinformationaboutit. Nowyouknowhowtouse'mkdir'.Youcanevenuseittocreateadirectorycalled 'my_enemies'ifyou'reintothatsortofthing.

The 'rmdir' command


'rmdir'istheoppositeof'mkdir'itgetsridofdirectories.Itshouldbepointedoutthat inordertouseit,thedirectoryhastobeempty.Ifyoucopiedormovedanythingto 'my_friends'andyoutyped rmdir my_friends/ Linuxwouldpolitelytellyouthatyoucan'tdothat. So,youhavetouseyour'rm'commandonthefilesfirsttoremovethemoruse'mv'to getthemintoanotherdirectory.Thenyou'refreetouse'rmdir'.So,nextwe'lldeal withthe'rm'command.

The 'rm' command


'rm'isforremovingordeletingfiles.Thatmeans,sendingthemintononexistence, oblivion,byebye.

The correct use of 'rm'


Soyouhavetobecarefulwith'rm'.That'swhyweputanentryintoour'.bashrc'file: aliasrm='rmi'sothatitasksyouifthat'swhatyoureallywanttodo.

42

Ifyoucreatedafilecalled'bad_jokes'andyouwantedtogetridofthefile,youwould typermbad_jokes,andbecauseyoumadeanalias,itwillaskyou. rm: remove `bad_jokes'?: Youwouldpressthethe'y'keyunlessofcourseyourememberedthatyouhaveareal goodoneinthereandthenyouwouldanswer:withthe'n'key.Actually,anykeyother than'y'isthesameasrespondingwiththe'n'key,soifyouaccidentallytype'w',don't worry.

'rm' some words of caution


Youcanalsodostufflikermb*withtheasterisk,butIwouldusemybestjudgment withthat.Youmayget'yitis'andjustkeeppressingthe'y'key.Ihavedonethat before. Occasionally,whenI'veusedthetexteditor'joe'alotIendupwithalotoffilesthat end in a tilde (~). You get files like 'note_to_myself1' and if you've modified it, anotherone'note_to_myself1~'ThenIdecidethatIdon'twantallofthose~files litteringupmydirectoryandIinnocentlytype:'rmnote_to_myself*'andthen'y''y''y' andthenIrealizetoolateandmybraintypes:'Ydidyoudothat!!"Theproblemis that'note_to_myself2'containedmyimportantplansfortakingovertheworldand 'note_to_myself3'containedanoteabouthowmuchmoneyIoweatthedrycleaners. Maybetakingovertheworldcanwait,butmydrycleaner'snotgoingtogivememy suitsthenexttimeunlessIpayhim. There'sanothercaseof'rm'that'spotentiallymoredangerousthanthe'rm*'case. That'saddingthe'f'optionontheend.Ifyoudothis,itwilloverridethe'i'option andwon'taskyouanything.Itjustgoesaheadanddeletesthefilesinquestion.For example,ifyouwereinadirectoryandtyped'rm*f'youwoulddeleteeverything, noquestionsasked.Igenerallyusethe'f'optionverysparingly,likewhenValentine's dayfallsonFridayduringleapyearandcoincideswithafullmoon. Also,pleasebeverycarefulwhenyou'reusingthe'rm'commandas'root'.Youcould dosomeveryserioussystemdamageifyoudeletethewrongfiles.Waituntilyou have some experiencebefore youstart removing files 'by hand' as 'root'. Use the configurationtoolsprovidedinyourversionofLinuxtouninstallprogramsthatyou don'twant.

43

Lesson Seven
Plumbing with pipes in Linux
Inthislesson,we'regoingtodoalittleplumbing.Plumbingwithacomputer?Well, Linuxissoflexiblethatitevenallowsyoutodoplumbingwithit.Well....actually, it'sjustalittlewitticismofminebecausethecommandwe'regoingtolearninthis lessoniscalled'pipe',andplumbersworkwithpipes.142Using'pipe'Toshowyou how to use thecommand'|'to executemorethan one commandTo usethe pipe command, you don't type: pipe. You press the '|' key. The location will vary on keyboardsfromcountrytocountry.Thissymbolisliketwoverticalslashes,oneon topoftheother. Thisisthefirsttimethatwe'regoingtoseeacommandthat'smeanttobeusedwith othercommands.Thatmeansthatthepipewillseparatetwocommandssothatthey willbedoneoneaftertheother.Let'strysomeplumbing. Forexample,ifyoulookedatthecontentsofyour/procdirectorywith: ls -l /proc itwouldbetoobigtofitinonescreen.Soifwetyped ls -l /proc | more youcouldscrolldownwiththeENTERkeyandseeitall. Actually,lsl/proc|lessisabettersolutionbecauseyoucanscrollupanddownwith the arrowkeys. Rememberthatinaprevious lessonwe said:"Less ismorethan more". You'reprobablygoingtoendupusingthisalot.You'repersonaldirectoryin/home willfillupandprettysoon'lsl'willoverflowinyourterminalorxterminalwindow. There'salittleshortcutifyou'veforgottentousethepipe.Youcanalsoscrollupand downinaterminalwiththeSHIFTPAGEUP/SHIFTPAGEDOWNkeys.

Redirections
tee
Inthelessononthepipecommand,ImentionedplumbingwithLinux.IthinkI'm goingtoresistthetemptationtomakesomesortofgolfreferencehereinthelessonon thecommand'tee'. 44

'tee'isusedtowriteoutwhatappearsonyourscreenintoafile.Youwillbeusingthis withtheafterapipe'|'. Youmightdothis: ls -l | tee directory_listing togetafilewiththelistingofadirectory.Ifyou'veplacedfilesinadirectorytobe backedup,youcouldusethiscommandtocreatealistingofthatdirectory.Youcould printoutthefileonalabelandstickittothedisk,tape,zipcartridgeorwhateveryou usedtomakethebackups. Ifyou'reusingthe'tee'commandforthebackupsIdescribedbefore,youmaywantto putadateonthefile.Youcanusethiscommand: date | tee -a directory_listing Thecommand'date'willenterthedateandtimeinthefileattheend.Rememberto usetheaoptionifyou'regoingtowritetothatfileasecondtime.Ifyoudon'tyou willeraseeverythingonthefileinfavorofwhateverthesecondcommandwas.

The '>' command


The "greater than" symbol '>' will do the same as 'tee'. You don't need the pipe command(|)withthisone. ls -l > directory_listing willgiveyouthesameresult.Ifyouwanttoaddthedateattheend,usethecommand: date >> directory_listing withtwo"greaterthan"symbols(>>).Thetwosymbolswilladdtothefilewithout erasingitscontents.

The '2>' command


Thiscommand,thenumbertwo(2)withthe"greaterthan"symbol>,isusedfor creatingafileforanerrormessagethatyoumayget. YouwillprobablynotbeusingitalotbecauseweallknowhowperfectLinuxisand howfewerrorstherearewhenyou'reusingit.Buteveryonceandawhileyoumay wanttodownloadsomesoftwarefromtheInternetYouinstallitandwhoops! there'ssomeerror.Youmaynothavesomethinginstalledthatthetheprogramneeds torun.Youcouldjustdosomethinglikethis: [program X that doesn't work] 2> program_X_error Youcreateafilewiththeerrormessage.Youcouldshowittosomeonewhomight knowwhat'smissingoryoucouldsendittotheauthoroftheprogram.Heorshe wouldalsoliketoknowaboutitandwillprobablyhelpyoufixit. xargs...

45

Lesson Eight
How to get more information with Linux
Nowwe'lltalkaboutsomeothercommandsthatyouwillprobablyneedinyourdayto day work with Linux. They make your work a little easier and give you added informationaboutyoursystem.

'man' manual pages in Linux


To show you how to get more information from the manual pages and other documentation sources The first command is 'man' This command will show the manualforacommandorprogram.Themanualisafilethatshowsyouhowtouse thecommandandlistthedifferentoptionsforthecommandinquestion.Youwould type: man [the command] Forexample,ifyoutype man mkdir Themanualfilefor'mkdir'willcomeupandgiveyouadetailedexplanationofthis command.

Managing documentation in Linux


Themanualfilefor'mkdir'isactuallyoneofthemorestraightforwardones.There arealotthatIthinkwe'rewrittenbyHarryBigbrainsandtheyweremeanttobeseen onlybyRichardBiggerbrainwho'ssittinginthecubiclenexttohim. Forexample,thisappearsinthe'man'filefor'cp'
Bydefault,sparseSOURCEfilesaredetectedbyacrudeheuristicandthe correspondingDESTfileismadesparseaswell.Thatisthebehaviorselectedby sparse=auto.Specifysparse=alwaystocreateasparseDESTfilewheneverthe SOURCEfilecontainsalongenoughsequenceofzerobytes.Usesparse=neverto inhibitcreationofsparsefiles.

Idon'tknowaboutyou,butI'mgoingtocallmylawyer.I'vebeenassaultedby"a crudeheuristic". Ifyouusethecommandcphelp,you'llgetanutshellversionofthe'cp'command.If youuseyourpipecphelp|less,it'llbealittleeasiertomanage.

The 'info' format


46

Typinginfo[commandname]willgetyoumoreinformationonacommandandis morecurrentthanmostmanfilesandperhapsalittlemorereadable.Infact,some 'man'fileswillactuallytellyoutoconsultthe'info'file.The'info'filesarenotalways installedautomatically.soyoumaywanttoconsultyourownversionofLinuxabout thesefiles.

Apropos
Theword'apropos'meanspertinenttosomethingelse.Thereisacommandthatwill showyouallofthemanpagethatmayshedsomelightonacertaincommand.For example,ifItyped:
apropos xterm

Iwouldgetsomethinglikethis:
resize (1x) - set TERMCAP and terminal settings to current xterm window size xterm (1x) - terminal emulator for X terms (5) - database of blessed terminals for xtermset. xtermset (1) - change settings of an xterm

Theseareallmanpagesrelatedtoxterm.Youwouldthenjustchooseoneoftheseand type man terms forexample. SomeversionsofLinuxthataremadeforlanguagesotherthanEnglishwillgiveyou thisdocumentationinitsparticularlanguage.Therearealsowebsitesthatspecializein documentationinotherlanguages.YoucanuseyourfavoriteInternetsearchengineto findLinuxdocumentationinyourownlanguage.

47

Lesson Nine
Other interesting and useful commands
The command 'touch'
Nowwe'regoingtotalkaboutatouchysubject.Thecommand'touch'whichisusedto changethetimeand/ordateofafile. You can use 'touch' if your boss yells at you about not having a report ready at lunchtime.Youshouldquicklyfinishthereport,thentype: touch -t 05070915 my_report.txt anditmakesitlooklikeyoudiditat9:15.ThefirstfourdigitsstandforMay7(0507) andthelastfour(0915)thetime,9:15inthemorning.Makesureyourdigitsmatch yourstory.Youdon'twanttohaveitlooklikeyoudiditinFebruary.Ofcourse,if youpunchedinat9:40,thenyou'reintrouble. 'touch'canbeusedalsotocreateanemptyfile.Youwouldjustenter touch[afile name].Theremaybetimesinthefuturewhenyouneedanemptyfilethatwillbe filleduplaterautomaticallybytheworkingsofsomeprogram.We'lldealwiththe usesof'touch'inourlatercourses.

Finding things with the command 'find'


There'ssomuchonacomputer'sharddrive,nobodycouldeverknowfrommemory where everything is.Perhapsthe smartladwhowonthespellingbeebyspelling 'prestidigitator'mightbeableto,butmostofusaregoingtohavetofindthingsnow andthen. IfyouuseawindowsmanagerlikeKDE,youcanusethefindtool.It'sveryuseful becauseithasalotofoptionsandyoucanusethemtomodifyyoursearches. Butifyou'regettingusedtousingcommandlinestuff,justtypein: find -name *hawaii* andfindoutwhereyouputyoupicturesofyouHawaiianvacation.Ifyou'reinyour/ homedirectory,itwillgothrougheverydirectoryandfindeveryfilethathasthe name'hawaii'init. Thetwoasterisksmakesureitdoesthat.Iftheystartedwith 'hawaii'youwouldn'tneedthefirstasteriskbutyoucanleaveitthereifyouwant.

48

Youmayhavecreatedsomefilerecently.Forexample,youmaywanttofindsome filethatyouwereworkingon,let'ssayfromnowupto10minutesago,youcould type. find -mmin +0 -mmin -10 Thiswilllistthefilesthatyoucreatedormodifiedwithinthelasttenminutes.Ifyou choosetouseahighernumberformmin?youshouldprobablyuseapipe,for example: find -mmin +0 -mmin -120 | less willfindthingsthatyoucreatedormodifiedupto2hoursagoandthe'|less'partwill makeiteasiertoread.

The 'grep' command


Inthelastsectionwetalkedaboutthe'find'commandwhichfindsfiles.Nowwe'll talkaboutthe'grep'commandwhichfindswordsinfiles.Yourwindowsmanager mayhavethisincorporatedintoitsfindtoolbutthenagain,thebeautyofLinuxis havingalternatives. 'grep'isaVulcanwordthatmeans"find".Actuallyitisn't,butitsortoflookslikeit, doesn'tit? Kirk:"FindthesolarsystemL10J,Mr.Spock." Spock:"Greppingnow,Captain."* Let'shavealittlepracticesessionwith'grep'.Thebestwayislearningbydoing,so let'sdoit.
*StarTrekstuffcopyrightParamountPictures

With'pico'oranyLinuxtexteditor,createafilecalled'mary1.txt' pico mary1.txt Thentype: Mary had a little lamb PressCTRLXin'pico'(ifyou'reusingthat)anditwillpromptyoutosave. Thencreate:mary2.txtandenterthetextMaryhadalittlecow. Savethatandcreatethefile:mary3.txtandtype:Maryhadalittletoomuchto drink.NowweknowwhatMarywasdoingwhenshewasn'twatchingherlambs! Nowsavethatfile. OK,nowwe'rereadytotryout'grep',sophasersonstunandlet'sgo.Typethe followingcommand: grep Mary mary*.txt

49

Let'sexplainthisalittle.'grep'looksfortheword"Mary"inanytextfilethatiscalled "mary(something).txt".You'vecreatedthreefilesthatstartwith'mary',sotheasterisk makessurethat'grep'willlookfortheword'Mary'inallthree. Youshouldgetthisoutput:


mary1.txtMaryhadalittlelamb mary2.txtMaryhadalittlecow mary3.txtMaryhadalittletoomuchtodrink

Theword'Mary'isinallofthosefiles,soyou'llgetthisoutput. Ifyoutypegreplittlemary*.txtyou'llgetthesameoutputbecausetheword"little" isalsoineachofthosefiles.Butifyoutypetheword"cow",you'llgetthisoutput:


mary2.txt:Maryhadalittlecow

becausetheword"cow"isonlyinmary2.txt. Typinggrepdrinkmary*.txtwillgetusmoreorlessthesame,onlythatmary3.txt willshowupinsteadofmary2.txt. Well,there's'grep'inanutshell.It'sbeenapleasure'grepping'withyou!

50

Lesson Ten
Power user commands
Hereisabriefoverviewofsomeothercommandsthatyoumayfindinterestingat somepointasyouuseLinux.TheywillhelpyoutogetallofthepoweroutofLinux.

'who'
'who'isacommandtofindoutwho'sworkingonyoursystem.Asyounowknow, Linuxisamultiusersystem.Evenifyou'reusingonecomputeratyourhome,you maybeworkingasmorethanoneperson.Forexample,ifyouloggedinas'root'but areworkingas'bob'.Youmayseesomethinglikethis: root tty1 May20 09:48 bob tty2 May20 10:05 ThisisjustLinux'swayofsayingthat'root'startedworkingonterminal1onMay20 at9:48inthemorningandbobstartedworkingonterminal2at10:05.Thisismainly usedinnetworkedsituationssothesystemadministratorknowswho'sworking.Itcan beusedbyyourbosstofindoutthatyou'vecomeinlatetoo.Youmayuseittofind outifyou'veopenedmorethatoneterminalsothatyouremembertologout.

Other commands
'whoami'
whoami isanicelittleprogramthattellsyouwhoyouare,justincaseyoudidn't knowalready.Youamnesiavictimsareinluck!Actuallyittellsyouwhoyouarein termsofhowLinuxunderstandswhoyouare,thatistosay,yourusername.Soif yourusernameisbobandyoutypewhoamiyou'llget: bobThiscomesinhandyif you switch terminals a lot and work as a different user. You may, in terms of computeruseanyway,forgetwhoyouare!

'whatis'
'whatis'isacommandsoyoucanfindoutwhataprogramdoes.Ifyouexploreyour Linuxsystem,youwillfindalotofprogramsandyoumaynotknowwhattheydo. Youwouldsimplytype:whatisgrepforexample,andyouwouldgetthis:
grep (1) - print lines matching a pattern

51

Linuxisgood,butit'snotallknowing,soifyoutype:whatisorangejuiceYouwill getthismessage:
orange: nothing appropriate. juice: nothing appropriate.

basicallytellingyouthatLinuxhasnoideawhatorangejuiceis.

'whereis'
whereisisanicecommandforfindingothercommandsorprograms.Ifyoudecideto downloadanyprogramfromtheinternet,thatprogrammayneedotherprogramsin ordertowork.Ifyouwanttoknowwhetherornotyouhaveit,youcantype:whereis [programname]andfindout. Ifyouwantedtofindoutifyouhavethe'pico'editorandwhereitis,youwouldtype: whereis pico andyoumaygetthis:
pico: /usr/bin/pico /usr/man/man1/pico.1.gz

Itshowsyouwherethecommandisaswellasthelocationofitsmanualfile.whereis isn'tdesignedtofindpeople,soifyoutype whereis Harry LinuxisjustgoingtosayHarry:

'which'
Toshowyouanothertoolforlocatingprograms'which'issimilarto'whereis'.Itwill giveyouthelocationofaprogram.Attimes,aprogrammaynotfindanotherprogram itneedstomakeitrun.Itwillneedtoknowitslocationor"path".Forexample,a programmayneedJavatorunitbutthinksitsinanotherplace.Youwouldsimply type: which java andLinuxwillinformyouofitslocation
/usr/lib/java/bin/java

Thisisahandycommandbecausesomelocationsofprogramsvaryfromoneversion ofLinuxtothenext.Asoftwaredevelopermayhavedesignedhis/herprogramto accessJava,forexample,fromadifferentlocation.AsOpenSourcesoftwarewill alwaysletyoumodifyconfigurationfilestogetyourprogramworkingaccordingto yourneeds,youcangettheprogramtoworkforyoursystem.

'echo'
Toshowyousomeusesofthe'echo'command'echo'isalittlecommandthatrepeats anythingyoutype.Forexampleifyoutype echohello Linuxwilldisplaytheword 'hello'.

52

Thereisreallynoneedtodothatundernormalconditions.Youmayfind'echo'useful inthefutureifyoustartwriting"shellscripts"whicharelikelittleprogramsthatyou couldusetodoafewcommandsatonetime.Youcoulduse'echo'inthosescriptsto tellyouwhatthescriptisdoingatanygiventime,ortopromptyoutodosomething, likeentertext.Shellscriptswillbetakenupinalatercourse. Thereisapracticalusefor'echo'ineverydaylife.Isometimesuseittowriteshort notes.Ifweuse'echo'alongwith'pipe'(|)and'tee',you'vegotapoorman'spostit note.Forexample:


echo remember to tell Bill Gates he owes me 5 bucks | tee -a bill_gates.note

Willmakeyouaniceremindernoteaboutdear'oleBill.Justremembertoreadyour note.Youcouldtype:
echo remember to open Gates note | tee -a remember_gates.note

tomakeyourselfareminderfortheotherremindernote.Uselessbill_gates.noteor lessremember_gates.notetoreadyournotes.

'wc'
People following this course from Europe may recognize this as the symbol for 'bathroom'.Unfortunately,ifyoutypethisinyourterminalitwillnotshowyouthe way to the'facilities'.Actually, thiscommandwill giveyouthenumber of lines, wordsandletters(characters)inafileandinthatorder. Let'sgobacktothefileaboutthepeopleIowemoney.IfItype: wc people_I_owe_money.note Iwillgetthisoutput:
439 6510 197120 wc people_I_owe.note

Asyoucansee,thereare439lines,sothatmeansifeachlinerepresentsoneperson, thenIowe439peoplemoney.Thereare6510wordsandatotalof197120characters. Imightaddthatthisisagoodtoolforpeoplewhowritelettersprofessionallyandget paidbytheword.

Miscellaneous commands
Thesemightcomeinhandyfromtimetotime.

'dir'
ThepeoplewhotraveleddowntheMSDOSroadwillknowthisone.Actually,dir=ls l.Itwillgiveyouthesameresult.Ifyoudoanydownloadingoruploadingoffiles via FTP bywayofanonGUIFTPprograminyourterminal,youmayfindthis commanduseful.Ionceranintoacasewheretheremotecomputerdidn'trecognize thelslcommand.Ijusttypedindirandthatdidthetrick.ThenIfiredoffanastye mailaskingwhyintheworldtheyweren'tusingLinux! 53

'pwd'
Thecommandpwdwillshowcompleteinformationonthedirectoryyou'reworking in.Forexample,ifyoutypepwdyoumaygetsomethinglikethis:
/home/bob/homework

whichshowsyouthatyou'reinthedirectory'homework'inyouruserdirectoryas 'bob',soyouknowexactlywhereyouare.

'date'
Didyouforgetyourweddinganiversary?Yourboyfriendorgirlfriend'sbirthday?Tax day?(everyonewantstoforgetthatone!)Noneedforthattohappenanymorewith Linux.Justtype: date You'llgetthis:(orsomethinglikeit,actually.IfyougetthesamethingasIdo,then I'dconsiderbuyinglotterytickets)
Thu Sep 7 20:34:13 CEST 2000

Youprobablygeteverythinghere.Ifyou'relivingincentralEurope,youwillrecogize the'CEST'part.Thatstandsfor'CentralEuropeanStandardTime'.Linuxrecognizes worldtimezonesandyousetthisupwhenyouinstalledLinux.IfyouliveonMars, you'reoutofluck,unfortunately. Thereareotherusesofthe'date'command.Toseejustthedate,type: date +%D Toseejustthetime,type: date +%T ToseeonwhatdayChristmasfallsthisyear(really,I'mnotkidding!),type: date --date 'Dec 25' andyou'llgetthedaythatChristmasfallsonthisyear.Substitutethatforanydatethat you'dliketosee. Therearemanyotheroptions.Consultyourmanualfile('mandate')or('infodate').

'cal'
Typingcalwillgiveyouthecalendarofthepresentmonthonyourscreen,inthenice standardcalendarformat.Therearealotofusefuloptions. Ifyoutype: cal2000 You'llgettheentirecalendarfortheyear2000.Substituteanyyearyoulike.Ifyou type: cal122000

54

You'llseethecalenderforDecemberof2000.Substituteanyyearormonthyoulike. Ifyouaddtheoptioncalm,theweekwillstartonMonday,asitispreferredinmany countries. Justforfun,Itypedcal101492andIfoundoutthatColumbusdiscoveredAmerica onaFriday.Thatwasgoodluckforhimbecausethatwayhegottorelaxforthe weekend.

'exit'
Asyoucanguess,youcangetoutofaterminalwiththe exit command.Ifyou're workingintextmode,typingexitwillpromptyoutologinagain.Ifyouwanttowork asanotheruser,uselogoutinstead. Ifyou'reinxwindows,exitwillclosetheXTerminalyou'reworkingwith.exitwith theoption"stageright"willgetyouanerrormessage.

An introduction to aliases
Inthatfile,youcanaddsomethingcalledan'alias'.Everybodyknowswhat'alias' means'anassumedname'.An'alias'inthisfilearesomelinesthatyouwritesothat yourbashshellassumesthatonecommandisreallyavariationofit.Asyoualready know,youcanmodifyacommandwithaslash''andaletterToseewherethe.bashrc filewas,youcouldhavetyped'lsa'andthatwouldhaveshownyoueveryfileinthe directory,includingthosethatstartwith'.'Ifyoufindyourselfusingthese'letter' combinationsalot,youcanmodifyyour.bashrcfilesothateventhoughyoutypethe simplecommand,like'ls',youactuallyget'lsa'. Someofthesealiasesmaybeveryimportanttokeepyoufromsendingthatnovelyou justwroteintononexistencebyaccident.Ihaveacoupleofentriesinmy.bashrcfile tokeepmefromgettingintotrouble.Theyare: alias cp='cp -v -i' alias rm='rm -i' alias mv='mv -i' Letmeexplainthem. 'cp'isthecommandtocopyafiletoanotherplaceortomakeacopyofafileundera differentname.Inordernottocopyafiletoaplacewherethere'salreadyafilebythe samename,youcouldtypecpvi,(vforverbose,iforinteractive)anditwouldask youifyoureallywanttodoitincasethere'sanotherfilebythesamename.Thenthe vwouldshowyouwhereitwent.Thisisprobablyagoodideaallthetime,soyou couldcreateanaliasforitinyour'.bashrc'file.

55

'rm'istheremove/deletecommand.InLinux,thismeansgoneforever[cueominous organmusic]Youobviouslyhavetobeverycarefulwiththisone,becauseinthebash shellthereisreallyno'trash'buckettopickitoutofifyoudeleteit.That'swhyI've addedthei(interactive)commandtomyalias,sothatitasksmeifIreallywantto deletethatnovelIjustwrote. 'mv'isformovingfilestoadifferentplaceorrenamingafile.Ihaveanaliasforitfor thesamereasonsasthe'cp'command.

56

Lesson Eleven
Another Look at Users
Ifyou'rethesystemsadministrator,regardlessoftheenvironment(large,mediumor smallorganization),oneofyourtasksisgoingtobetoadduserstothesystem.This meansgivingapersonauseraccountononeormoremachinesinyournetwork.The mainissuesthatyouhavetodealwithistodecide,basedoneitheryourownorthe company'scriteria,whatprivilegestheuserisentitledto. Ifyou'reinterestedinhavingtightercontroloverhowyoucreateusers,youshoulduse thestandardcommandlinetooluseradd.Let'slookattheoptionsavailabletoyou. First,ifwerunthefollowingcommand: useradd -D Youwillseehowusersareaddedtothesystembydefault. GROUP=100 HOME=/home INACTIVE=-1 EXPIRE= SHELL=/bin/bash SKEL=/etc/skel Let'sdissectthisabit.Inthisexample,anyuserwillbeaddedtoagroupcalledusers. Ifyoulookedat/etc/group,whichliststhenamesofthegroupsonyoursystem,you'll findnumber100asbeingassignedtousers.Thisisadefault,catchallgroupofsorts, thatincludesallusers. Asyoualreadyknow,auseraddedtothesystemwillbegivenadirectorytokeephis orherfiles.Thisiscreated,bydefault,in/home.TheINACTIVE=1referstothe numberofdaysittakesforthesystemtolockyououtwhenyouraccountexpires.As youcanseehere,yougetlockedoutrealsoon! EXPIRE=referstoadatewhenyouraccountissupposedtoexpire.Inourexample, thereisnodate.Thisisprobablyfineforregularemployees,butifyouhiredsome outsideconsultanttodoworkforyou,youmightwanttohisorheraccounttoexpire at the conclusion of business. The best way to handle temporary workers (and especially fired employees) is to delete the account entirely. But even the best administratorsareoftenoverworkedandmayforget,sosettinganexpirationdatewill ensurethatanaccountcannotbeused.

57

The next item, SHELL=/bin/bash, refers to the shell that users will have to run commandsonthesystem.Bash, ortheBourneAgainShell,isstandardonLinux distributions.Thatdoesn'tmeanthatyouasasystemadministratorcan'tinstallother shellsonthesystemandmakethemthedefault(TheKornshell,forexample).The lastitemisveryimportantforyouasanadministrator.SKEL=/etc/skelmeansthatthe fileslocatedin/etc/skelwillbecopiedtotheusersdirectorywhenyoucreatethe account.Youmaywanttoaddfilestothisdirectoryoryoumaywanttomakechanges tothem. Feel free to change the values 45m and 33m if you don't like those colors. Not everybody'sintomagentaandyellow! Nowyou'rereadytoadduserstothesystemwithmoreselectivecriteria.The"man" pageforuseraddisoneofthebetteronesforaLinuxcommand.Hereyoucanseeall thepossibleoptionswithgoodexplanationsaboutwhateveryonedoes.Let'slookat anexampleusingsomeofthemostcommonoptions. useradd -c "William Shakespeare - AKA, The Bard" -d /home/wshakespeare -m -k /etc/skel -g 100 -s / bin/bash wshakespeare Let'sseewhatwe'vedone.First,we'veaddedWilliamShakespeareasausertoour system.Thefirstoption,c,isashortcommentthatmustcomebetweenquotation marksandhelpsidentifyouruserinthe/etc/passwdfile.Thesecondoption,dis whereyouwanthispersonaldirectorytobecreated.Themoptioncreatesthehome directoryandthekoptioncopiesthefilesinthefollowingdirectory(inourcase,/ etc/skel)there.Thegoptionputstheuserinthegroupwhosenumberfollows.Thes optionprovidestheuserwithashelltouse(inourcase,Bash).Finally,thenamethe userwillloginwith. Whatyoumayhavenoticedisthatwedidn'tusethep(password)option.Forthe timebeing,Shakespeareiswithoutapasswordandthereforecannotlogin.Thisisa bitmorecomplicated.MostLinuxdistributionsnowadaysuseasystemofshadow passwords.Theseareencryptedsothatanormalusercan'tlookatthepasswordsin thesystem.Theproblemwehavewithuseradd,isthatitneedsanalreadyencrypted password toworkcorrectly. Let'ssayIwantedtogiveShakespearethe password 'h4ml3t'.IfIaddedph4ml3t,thesystemwouldrejecthisloginbecauseitwasn't encrypted.Ifyoulookedatthe/etc/shadowfilewheretheseencryptedpasswordsare stored,you'dfindsomethinglikethisnexttoauser'sloginname: Q37spqpXAsl1Y Userjsmithmayhavethepassword'mrT1bbs'butitwouldappearassomethinglike jsmith:F54spqpRAsl1X:12043:0:99999:7::: in/etc/shadow.Thisisbecausethepasswordhasbeencreatedasanmd5hash,which isanencryptionalgorithm.So,thebottomlinehereisthatyouhavetwooptions.An administratorthatsimplyneedstoaddanaccounthereandtherecanusetheoptions above,minusthepandthenrun passwd user 58

andprovideapassword.passwdwillthencreatethemd5hashautomatically.Ifyou foundyourselfneedingtocreatemanyusersatthesametime,youmightwanttolook intosometoolsthatcreatethesehashesbeforehandandthenyoucanprovidethem withthepoption.

Deleting Users
Asanadministrator,youwillneedtodeleteusersaswell.Peopleleaveandmoveon tootherthings.Theycomeforshortperiodsandneedtemporaryaccounts.Accounts needtobedeletedwhentheyarenolongergoingtobeused.Thisisofmaximum importance from a security point of view. We've all heard stories of disgruntled formeremployeesloggingbackintotheiraccountsandusingthesystemtoeither embarrasstheirformeremployersbyplayingpranksortoactuallytrytodoserious damage. Again,aswestatedbefore,yourLinuxdistributionchoicemayhavetoolstodothis. Somemakethiseasierbyalsodeletingusershomedirectory(andallthefiles!)along with theaccount.Thestandardtool thatcomes withalldistributions, however,is deluserItissimplyrunlikethis: userdel wshakespeare whereyousubstitutethewshakespearewiththeusernameyouwishtodelete. Inthisparticularcase,we'vedeletedWilliamShakespeare'suseraccount,butnothis homedirectoryandfiles.TogetridofanytraceofoldWill,thenyouwouldusether option: userdel -r wshakespeare whichwouldremoveeverything,includinghisemail.Wemaynotwanttodothis, however.Manypeopleleaveleavetheiremploymentbuttheirworkremainsproperty ofthecompanybecauseofcontractualobligations.Inthiscase,wewouldobviously wanttokeeptheuser'sfilesuntiltheycouldbelookedat,copiedtoanotheruser's accountorstored.Sobeverycarefulwiththeroption.

File permissions in Linux


LinuxhasinheritedfromUNIXtheconceptofownershipsandpermissionsforfiles. Thisisbasicallybecauseitwasconceivedasanetworkedsystemwheredifferent peoplewouldbeusingavarietyofprograms,files,etc.Obviously,there'saneedto keepthingsorganizedandsecure.Wedon'twantanordinaryuserusingaprogram thatcouldpotentiallytrashthewholesystem.Therearesecurityandprivacyissues hereaswell.Let'sfaceit,wedon'twantBilltoreadBob'sloveletterstotheJanetwho worksinR&D.(becauseJanetisBill'sfiance)Intheend,it'simportanttoknow whatbelongstome,toyouandtoeverybody. Aswementionedatthebeginningofthiscourse,thebigadvantagethatLinuxhasis itsmultiuserconceptthefactthatmanydifferentpeoplecanusethesamecomputer 59

orthatonepersoncanusethesamecomputertododifferentjobs.That'swherethe systemoffilepermissionscomesintohelpoutinwhatcouldbeaveryconfusing situation.We'regoingtoexplainsomebasicconceptsaboutwhoownsthefileand whocandowhatwithafile.Wewon'tgetintoanenormousamountofdetailhere. We'llsavethatfortheLinuxsystemadministrationcourse.Wewillshowyouhowto understandfilepermissionsymbolsandhowtomodifycertainfilessothatthey're moresecure.

File permission symbols


Ifyourunthecommandlslinyourhomedirectory,youwillgetalistoffilesthat mayincludesomethinglikethis
rwrr1bobusers1892Jul1018:30linux_course_notes.txt

This basically says, interpreting this from RIGHT to LEFT that the file, linux_course_notes.txtwascreatedat6:30PMonJuly10andis1892byteslarge.It belongstothegroupusers(i.e,thepeoplewhousethiscomputer).Itbelongstobobin particularanditisone(1)file.Thencomethefilepermissionsymbols. Let'slookatwhatthesesymbolsmean: Theslashmarksseparatethepermissionsintothreetypes Thefirstpartreferstotheowner's(bob's)permissions. Theslashmarkbeforetherwmeansthatthisisanormalfilethatcontains anytypeofdata.Adirectory,forexample,wouldhaveadinsteadofaslash mark. The rw thatfollowsmeansthat bob canreadandwriteto(modify)hisown file.That'sprettylogical.Ifyouownit,youcandowhatyouwantwithit. The second part of the these symbols after the second slash, are the permissionsforthegroup.Linuxcanestablishdifferenttypesofgroupsforfile access.Inaonehomecomputerenvironmentanyonewhousesthecomputer canreadthisfilebutcannotwriteto(modify)it.Thisisacompletelynormal situation.You,asauser,maywanttotakeawaytherightsofotherstoread yourfile.We'llcoverhowtodothatlater. Afterthetwoslashmarks(twoherebecausethereisnowritepermissionsfor thegroup)cometheoveralluserpermissions.Anyonewhomighthaveaccess tothecomputerfrominsideoroutside(inthecaseofanetwork)canreadthis file.Onceagain,wecantakeawaythepossibilityofpeoplereadingthisfileif wesochoose. Let'stakealookatsomeotherexamples.Aninterestingplacetolookatdifferent kinds of file permissions is the /bin directory. Here we have the commands that anybodycanuseontheLinuxsystem.Let's lookatthecommandforgzip,afile compressionutilityforLinux.
rwxrxrx1rootroot53468May11999gzip

Asweseehere,therearesomedifferences. Theprogramname,date,bytesareallstandard.Eventhoughthisisobviously differentinformation,theideaisthesameasbefore. 60

Thechangesareintheownerandgroup.Rootownsthefileanditisinthe group"root".Rootisactuallytheonlymemberofthatgroup. Thefileisanexecutable(program)sothat'swhytheletterxisamongthe symbols. Thisfilecanbeexecutedbyeverybody:theowner(root),thegroup(root)and allothersthathaveaccesstothecomputer Aswementioned,thefileisaprogram,sothereisnoneedforanybodyother thanrootto"write"tothefile,sothereisnowpermissionsforitforanybody butroot.

Ifwelookatafilein/sbinwhicharefilesthatonlyrootcanuseorexecute,the permissionswouldlooklikethis:
rwxrr1rootroot1065Jan141999cron

'cron'isaprogramonLinuxsystemsthatallowsprogramstoberunautomaticallyat certaintimesandundercertainconditions.Aswecanseehere,onlyroot,theownerof thefile,isallowedtousethisprogram.Therearenoxpermissionsfortherestofthe users. WehopeyouenjoyedthislittlewalkthroughoffilepermissionsinLinux.Nowthat weknowwhatwe'relookingfor,wecantalkaboutchangingcertainpermissions.

'chmod' explained
chmodistheprogramthatisusedtochangefilepermissionsonaLinuxsystem.As wementioned,otherscannotmodifyyourpersonaluserfilesbutyoumaynotwant otherpeopletoeven read thesefiles.Youcanusethiscommandtotakeawaythe possibilityofotherspryingintoyourprivatestuff. Thesyntax(partsseparatedbybrackets)forusingthiscommandisthefollowing:
chmod [a/o/g/u] [+ or -] (plus or minus sign) [r/w/x]

Let'sanalyzethesyntax: ThesymbolsinthefirstbracketsrefertothefourconceptsofusersthatLinux has. o a=all,allusers o o=others,(otherpeople) o g=group,themembersofyourgroup o u=user,(thismeansyou) Thesymbol+addspermissionsandthesymboltakesthemaway.Aswesay intheLinuxworldchmodgiveth,chmodtakethaway Youractualrightstofilesr=readrights,w=writerights(pardonthe homophonicredundancy!)andx=executablerights

Practical examples of chmod

61

Aswementionedbefore,youmaywanttorestrictrightstoreadafile.Youwould simplytype: chmod og-r my_world_domination_plan.txt Nownobodycanreadyourplanstotakeovertheworldexceptyou.Besttokeepthose secretanyway. WealsotalkedearlieraboutthosefilesthatyoumayhavecopiedfromaWindows partition or afloppyformattedfor Windows. Even if they'renot executablefiles, they'll show up as such (rwxrxrx). You can change them to their correct permissions,gettingridoftheexecutablestatuswith: chmod a-x the_file Rememberthatifyoucopiedthemas'root',youwillhavetousechmodasroottodo this.Youcouldevengoonestepfurtherandchangetheownershipofthefiletothe user you desire. You may want to change root ownership to yourself (your user name).We'llgointothisinthenextpartofthelesson.

Using chmod with number values


The permissions in Linux also can also be changed with number values. An accomplished Linux/Unix user will probably use this system more. When you're beginningwithLinux,themethodwedescribedbeforewillprobablybeclearerto you.Withoutgoingintotedioustechnicaldetail,we'lldescribethechmodnumber systemtoyouandlookattwoofthemostcommonexamples. AsIsaidbefore,wehavethreesectionstopermissions;thoseoftheownerofthefile followedbythoseofthegroupandthenthepermissionsofothers.Soifyouuse numbers with 'chmod', there will be three numbers following the command. One numbercorrespondstoeachgroup.Here'sanexampleofachmodcommandwith numbers: chmod 644 grocery_list.txt Ifyouhadused'pico'towriteupagrocerylistforyourtriptothesupermarkettoday, Linuxwouldhavegivenyou644permissionbydefault.Thatmeans,readandwrite permissionsfortheownerbutnowritepermissionsforthegroupandforothers.So thenumber6meansreadandwritepermissionsforyou,thenumber4meansread permissionsforthegroupandthelastnumber,4meansreadpermissionsforothers. Nowthequestionis:Whythesenumbers?Whynotothernumbers,likethenumber8 or12oreven1345?Let'sexplainthis. Thethreetypesofpermissionscorrespondtothreenumbers.Readpermissionisgiven avalueof 4.Thinkofitasthemostimportantpermission.(ifyoucan'treadafile, thenwhatelsecanyoudowithit?)Writepermissionisgivenavalueof2.Execute permissionisgivenavalueof1.Here'swhatitwouldlooklike: User(ortheowner) Group Others

62

readwriteexecute readwriteexecute readwriteexecute 421 421 421

It's really just a question of simple arithmetic. In our example of chmod 644 grocery_list.txt, we've added the 4 for read permission and to the 2 for write permission for the owner to get 6. We've just given the group and others read permission,sothere'snothingtoaddinthesetwogroups.Justgiveita4ineachcase. Presto!644.

Some practical examples with numbers


Let's take another look at my file that has my plans for dominating the world (my_world_domination_plan.txt). I had taken away the read permissions for everybody except myself using +/ letter method. (chmod ogr my_world_domination_plan.txt) Nowlet'sdothesamewiththenumbers. chmod 600 my_world_domination_plan.txt AsyoucanseeIhavereadandwritepermissionsforme(4read+2writeequals6) and0permissionsforeverybodyelse.TheZerovaluemeans7(maximumpermission value)minus4minus2minus1equals0.

Real worls examples with chmod


I'dliketotalkaboutarealworldpracticalexamplefordoingthis.Thereisacommand modeprogramcalled'fetchmail'forgettingyouremail.It'saverygoodprogramif you'reusingyourcomputerasdifferentusersforvariousjobs.Itwillsendmailtothe differentusersbasedonemailaddresses.Thedifferentaddressesarestoredinafile thatyoucreatecalled'.fetchmailrc'Thisfilealsoincludestheusernameandpassword for retrieving mail from each address. We've got a possible security hole here, particularlyifyou'renetworked.Thisfileshouldn'tbereadbyeverybody.Whenyou createyour.fetchmailrcfile,youmustthenusechmod600/chmodogronthefileto solvethesecurityissue.Infact,'fetchmail'won'trunifyoudon't.Itwillcomplain aboutthefile'spermissions. Let'slookatanother"realworld"example.Astheinternetbecomesmorepopular, websitesneedtobemoreuserfriendlyandinteractive.It'sbecomingmoreandmore commontousescriptstoimprovethequalityofawebsite'sofferings.Ifyouuseda languagelikeperltowritethescriptsandyouhostedyourwebsitewithacompany thatrunsLinuxontheirservers(wewouldhopethatyouwoulddothis!),youwould probablybegivenpermissiontousethesescriptsonyourwebsite.Youwouldthen havetogivethescriptsreadandexecutepermissionssothattheyourvisitorscould usethem.Afteryouuploadedascript toyourwebsite,youwouldthenissuethis command: 63

chmod 755 my_awesome_script andthescriptwouldbecome"executable"(andreadable)fortheoutsideworld.(74 read,2write1executableforyou,4readand1executableforgroupandothers).You couldalsousechmodog+rxmy_awesome_scriptThescriptisthen"converted"into a"program"sotospeak.Youhavealsoconvertedyourselfintoa"webdeveloper" withtherighttohangyourshingleonthedoor. chmodisoneofthosecommandsthatareusedmostbysystemadministrators.Inour Linuxsystemadministrationcourse,we'llgointothiscommandinmoredetail.Inthis lessonwe'veshownyoujustafewpracticalexamplestogetyourfeetwetwiththis veryimportantcommand.

Using chown
Thecommand chown isthe chmod'scousin.Itisusedforchangingtheownership rightsofafile(hencethename'chown'changeowner).Itdoesnotchangetheread, writeandexecutionpermissionshowever. Thiscommand,thoughavailabletoeveryuser,isprobablygoingtobeusedwhen you'reworkingasroot.Thecommandisuseslikethis: chown owner:group the_file Let'ssayyouwanttocopysomethingfromyourWindowspartition(ifyouhaveone). Youmountthepartition(asroot)andtosavetime,youcopythefiletoyouruser directory/home/bob/.Ifyoutypelslthe_fileyou'llgetsomethinglikethis:
rwrr1rootroot2428Nov1713:18the_file

Aswenowknowfromthepreviouslesson,rootistheownerofthefile.Therefore, rootistheonlyonewhohaswritepermissionsforthefile(permissiontomodifyits content).Ifyouplanonworkingwiththefileas"bob",thereisn'tasnowball'schance inhelltomodifythatfileuntil,asroot,yourunchmodonthefile.Solet'sdoit! chown bob:bob the_file ThisexamplepresupposesthatyourLinuxversioncreatesgroupsforeachuser.There areothersthatwillcreateagenericgroupcalled users foreverybodywhousesthe computer. On a network, groups are created according to the needs of the organization. Onyour single home computer, just type ls l andseewhat system correspondstoyou. Asyoucansee,'chown'isabsolutelynecessaryifyou'reworkingasmorethanone userwiththecomputer.

64

Lesson Twelwe
Taking care when working as root
AsImentioned,there'sachanceofdoingsomedamagewhenyouworkasroot.There areotherwaystoprotectyourselfbesidesputtingaliasesinyour.bashrcfile.Oneof themisusingtheprogramsu. suletsyouworkasrootwhenyou'reloggedinasanotheruser.Goodpracticedictates that you disallow root logins from remote machines, so if you're performing administrationtasksremotely,suisirreplaceable.Theremotemachineletsyoulogin asuserfred,forexample,andthenyoujusttype: su andtypetherootpassword.Forallintentsandpurposesyou'vegotarootterminal opennow.Thatmeansthatyoucandoanythingjustasifyouhadloggedinasroot inthefirstplace.You'rereallyrunningthesamerisksbyworkingasroot,butyou've atleasteliminatedtheriskoflogginginasroot.That'squiteimportantfromasecurity standpoint.Therealadvantagetousingsuisthepossibilitytocarryoutindividual commands. Let's say you've downloaded an application and it's only available as sourcecodeinatarball.Youcandownloadthesourcecodetoyouruserdirectoryand asauseryoucanruntheconfigureandmakescriptsprovidedwithmosttarballs.That way,youminimizetherisksofcompilingthesoftware.Ifyou'resatisfiedwiththe binaryfile(theapplicationitself),thenyoucanuse'su'toinstalltheapplicationand its accompanying documentation in the usual application and documentation directories.Here'swhatyou'ddo: su -c "make install" Youneedtoaddthec(command)switchandputtheactualcommandinquotes. Thentypetherootpassword. Asyousee,youcanrunanycommandthatrootcan.That,ofcourse,meansthatyou need to know the root password, so this is something that only the system administratorshoulddo.It'snotagoodideatobegivingyourpasswordtootherusers sotheycanruncommands.Theycandothatwithsudo,aswewillmentionsoon. Youcanalsousesutodothingsasotherusers.You'renotjustrestrictedtodoing thingsasroot.Thismightcomeinhandyifyou'vegottwoaccountsonamachine. Insteadofhavingtologinastheotheruser,youcould,forexample,readafilethat you've restricted permissions for. Let's say you've got a file called my_ideas and you've removed read permissions to it for your group and for others. Instead of loggingin,youcantype: su fdavis -c "less /home/fdavis/my_ideas" 65

andyouwillnowbeaskedforfdavis'password.Nowyoucanaccessfilesfromyour other useraccountwithout havingtologin.Otherusersmayalso giveyoutheir passwordstoaccessthingsintheiraccount.Iquestionthewisdomofdoingthat,but inanemergencyit'sanoption.Acoworkerwho'sillmaygiveyouhis/herpassword toaccessimportantfiles.That'sacceptableinthatkindofsituationitseems,buttheill workershouldpromptlychangehis/herpasswordassoonashe/she'sbackatwork. Asyoucansee,ifusedcorrectly,suisagreattoolforgettingadministrationtasks donesafely.It'salsousefulasatimeandtroublesaver.Justmakesureyoudon'tabuse it.

The use of sudo as alternative


Ifyou'retheheadsystemsadministrator(ortheonlyone)youcan"deputize"yourco workersbyinstallingandconfiguringtheprogramsudo.InUnix/Linuxspeak,the term'su'meanssuperuserthatis,root.Onlyroothastrueadministrationrightsand privileges, so this program allows others to "do" su, hence the name, sudo. Ok, Sheriff,timetofightthebadguys.Let'sseewhatyourdeputiescando. sucanalsostandforswitchuser.Forexample,ifyouhadtwoaccountsonamachine let'ssaybobandharryyoucouldlogonas'bob'anddo:suharryandthenworkas harry. Yourdistributionshouldhavethisverypopularprogramamongitspackages.Ifit doesn't, youcangoto:http://www.courtesan.com/sudoandget ToddMiller's great application.Afteryou'veinstalledit,youhavetocreatewhat'scalledasudoersfile. Youdothisbytyping: visudo asroot.Thisisessentiallyaspecialversionofthetexteditorvijustforcreatingand editingthesudoersfile. Here is an example sudoers file I have for my home network. It is notreallyas complicatedasmostare,butitgivesagoodbasicideaofwhatyouneedtodotolet otherusershelpyououtwithsomeadministrationtasks.
# # This file MUST be edited with the 'visudo' command as root. # # See the sudoers man page for the details on how to write a sudoers file. # # Host alias specification # User alias specification User_Alias TRUSTED = mike, maria # Cmnd alias specification

66

Cmnd_Alias INTERNET = /usr/sbin/traceroute, /usr/sbin/ntpdate Cmnd_Alias KILL = /bin/kill, /usr/bin/killall Cmnd_Alias TOOLS = /bin/mount, /bin/umount # User privilege specification root ALL=(ALL) ALL TRUSTED ALL=INTERNET, KILL, TOOLS

Let'sbreakthisdown.Firstofall,weaddtheline User_Alias TRUSTED = mike, maria Thatmeansthattheusersmikeandmariabecomethe"trusted"users.Andwhatare theytrustedwith?Jumpdowntothelastlineforasecond.Theyaretrustedwith commandsinthegroupINTERNET,KILLandTOOLS.Whatarethosecommands? Jumpbackuptothesection #Cmnd alias specification Thesetrusteduserscanusentpdate,forexample,tokeepthecomputer'stimecorrect. Moreinformationonthatcommandlater. I've created a KILL group (sounds like Mafia hit men!) so other users can kill runawayprocessthatcanonlybeshutoffbyrootnormally.Someserverprocessmay haveaproblemandyoumighthavetoshutdownthatprocess.Startingitagainis somethingthat'snotincludedherehowever.Itmightbebestforthesedeputizedusers callthe"real"systemadministratorandifthat'syou,forexample,youmaywantto checkouttheconfigurationfilesforcertainserversbeforeyoustartthemagain.You mayhavetomountfloppiesorotherpartitionstogetdatafromthem,andthat'swhere theTOOLSsectioncomesinhandy. Whentheuserexecutesacommandthat'sauthorizedinthesudoersfile,he/shefirst needstotype sudo andthecommand.Forexample,ifyouwantedtoupdatethemachinesclocktothe exacttime,youwouldtype: sudo ntpdate atimeserver.nearyou.gov/edu Thenyouneedtotypeyouruserpassword.Ifyoumakeamistake,sudowillhurl insultsatyou(nokidding).ToddMillerhasagoodsenseofhumorandtheresultsof botchingakeystrokearesometimeshilarious! Youcanaddmorecommandsanduserstoyourownsudoersfile.Whateveryouthink is prudent in your situation. There is some possibility for abuse. Use your best judgment.

Becoming a super user


Thefollowingcommandsarefrequentlyusedbysystemsadministratorstokeepan eyeonwhat'sgoingonwiththeirsystems.

67

'last'
Thecommandlastwillshowyouthepeoplewhohaveloggedintothecomputertoday andtheterminalstheyare/wereusing. Ifyoutype: last Youmaygetsomethinglikethis: fred tty6 ThuOct5 16:5520:05(3:10) bob tty1 ThuOct5 stillloggedin(3:10) root tty1 ThuOct5 16:2316:43(0:20) reboot systemboot ThuOct5 16:22 Asyoucansee,youworkedas'fred'for3hoursand10mins.Youarestillworkingas 'bob'.Youworkedas'root'for20minutes(probablysomeadministrationtasks)and youbootedyourcomputerat4:22PM. This is a good way to see who's been using the computer if it's networked. For example,ifyousawaanentryfor'satan'andyouhadn'tgiventhePrinceofDarkness permissiontologin,youcouldfireoffanastyemailtohimaboutmisuseofyour server.Hisaddress,bytheway,is"thedevil@hell.com".

'df'
'df'isacommandthatyou'regoingtousealotifyou'repressedforharddiskspace. Onceagain,therearemanyprogramsthatrungraphicallythatwillinformyouofthe spaceavailableonyourLinuxpartition.Butthisisaverygood,quick,nongraphic waytokeeptrackofyourharddiskspace. Ifyoutypedfyoumaygetsomethinglikethis.(ThisisactuallytakenfromasystemIuse fortestingversionsofLinux.You'llseeit'ssomewhatpressedforspace.) Filesystem 1024blocks Used Available Capacity Mountedon /dev/hda2 481083 40806248174 89% / Ifyoustartseeinga'df'outputlikethis,it'stimetogetdowntoyourlocalcomputer shopandbuyanewharddisk.Anyway,'df'isagoodwaytokeeptrackofthis.

'free'
'free'isacommandthatyoucanuseifyouwanttoknowhowmuchRAMmemory youhavefreeonyoursystem.Bytyping: free andyouwillgetsomethinglikethis total used free shared buffers cached

68

Mem: 14452 13904 548 28208 492 /+buffers/cache: 6100 8352 Swap: 33260 1556 31704

7312

Sometimes,ifaprogramisrunningparticularyslowly,youmayfindoutthatyour memoryusageishighusingthiscommand.Linux'smemorymanagementisquite goodbutacertainprogrammaybe"hogging"memory.Youcouldexitthatprogram andthentypefreeagaintoseeifitwastheculprit.

'du'
'du'isthewaytoseehowbigfilesare.Youcanuseitonadirectoryoronaparticular file.ThisisanothercommandIusealot.It'sprobablybesttousetheoptiondub(b forbytes)anditwillgiveyoutheexactfigureinbytes.Bydefault,'du'showsthe closestkilobytefigure.Let'slookatacoupleofexamples: IfItype: du people_I_owe_money.note Imaygetanoutputlikethis:
194 people_I_owe_money.note

Butinstead,ifItype: du -b people_I_owe_money.note I'llget:


197120 people_I_owe_money.note

Asyoucansee,it'sabigfile.Iowealotofpeoplemoney.Ontheotherhandlookat theoutputfor'people_who_owe_me_money.note':
1 people_who_owe_me_money.note

No,that'snotthekilobytefigure.That'sthebytefigure! Youcanalsousethisonadirectory,anditwilllistthefilesandsubdirectoriesand giveyouthebyteorkilobytecount,whicheveryouprefer.

Commands to control your system


'ps'
'ps'willgiveyoualistoftheprocessesrunningonyoursystem.Justtypingpswill giveyoutheprocessesyou'rerunningasauser.Itmaylooklikethis:
PID 293 1436 1437 1445 TTY 2 2 2 2 STAT S S S S TIME 0:00 0:00 0:00 0:00 COMMAND bash sh/usr/X11R6/bin/startx tee/home/bob/.X.err xinit/home/bob/.xinitrc

69

1449 1459 1461 1462 1464 1472 1730 1731 1760 1781

2 2 2 2 2 2 2 p1 2 p1

S S S S S S S S S R

0:01 0:00 0:00 0:00 1:27 0:00 0:00 0:00 0:01 0:00

/usr/X11R6/bin/fvwm2 /usr/X11R6/lib/X11/fvwm2/FvwmButtons74.fvwm2rc08 xclockdigitalFONT10x20geometry+520+550 /usr/X11R6/lib/X11/fvwm2/FvwmPager94.fvwm2rc0800& /opt/netscape/netscape (dnshelper) xtermFONT8x13backgroundWheatTxterm1 bash emacs ps

Ifyouhappentoforgetwhatyournameis,youcantypepsu.Thisistheusermode andyourusernamewillappearinthefirstcolumn.Actually,there'smorethanthat. Therewillbeothercolumnsaboutmemoryusage,thetimeyoustartedrunningthe processesandothers. Youcanseeotherusersprocessesifyoutypepsau.Ifyou'renotusinganetworked computer,youwillseeyoursandroot'sprocesses.Ifyou'reintodetectivework,you cantypejustpsaandtrytoguesswho'susingtheprocess. Theinformationthatyou'llprobablybemostinterestedinisthecolumnthatshows the"processID"or"PID".We'llgetintowhythesearesoimportantinthenextpartof thelesson.

'kill'
"kill"isaveryexplicitword.Itimplies'death'.Inthelastpartofthislessonwetalked about process IDs or "PIDs". Well, with the command 'kill' plus a PID, you can terminateaprogram.Inotherwords,youkilltheprogram.Youwillprobablyonlyuse thiswithtroublesomeprocesses;programsthatmaynotletyouexitregularly.Agood exampleofthisiswhenyoutryanewprogramthathasn'tgotallthebugsworkedout ofityet.Ifthe'exit'buttondoesn'twork,youcan'kill'it. Todothis,first,youwouldtypepsandyouwouldgetthisoutputthatwetalkedabout before. PID 293 422 437 438 441 TTY 2 2 2 2 2 STAT S S S S S TIME 0:00 0:00 0:00 0:00 0:01 COMMAND bash sh/usr/X11R6/bin/startx tee/home/bob/.X.err xinit/home/bob/.xinitrc /usr/X11R6/bin/evilaliens

70

Let'ssayyou'retryinganewgamethatwasjustportedtoLinux.Thegameiscalled "EvilandNastyAlienVisitors".Thenameofthe"binary"orprogramitselfiscalled evilaliens.(thelastoneonmy'ps'example)It'sabeta(i.echeckitoutandtellthe authorwhatbugsarestillinit)versionandthegamestartsgivingyouproblems.Now youcan'texittheprogrameither.ThealiensjusttookoverOklahomaandyouswore yougotthemall.You'replayinginyourxwindowsenviromentandyouhaveanx terminalopen(probablytheoneyoutyped'ps'into).Youwouldjusttypekillandthe PIDnumber,inmyexample,441.Thatis: kill 441 andtheprogramdisappears,alongwithallthosenastyaliens. Here'salittletrick.Ifyoudon'twanttodotwosteps,'ps'and'kill'andyouknowthe nameofthe"binary"orprogramitself,asImentionedbefore,youcanjusttype: killall evilaliens andthatshouldalsodothetrick.

Using 'kill' as root


Remember that when you work as root, you are the allpowerful master of the universe.(oratleastthecomputer).Whenyouuse'kill'asroot,youarethe007on Her Majesty's LinuxService.Youhavelicense to'kill'the process youdesire.If you'reworkingas'root'andyouneedtousethe'kill'command,it'sagoodideatorun psauandlookcloselyatyourPIDs.Youdon'twanttoendupkillingsomeprocess thatyouneed.

Another way to kill a process


Trytypingthis:find*.(Kindofanabsurdthingtodo,butgoodasanexample)Itwill juststartfindingeverything.Ifyouhavedonesomethinglikethisbymistake,youcan usethekeysCTR+Ctostopthe'find'process.Inthesecases,there'snoneedtouse the'kill'command.

Job control
Ctrl+Z...jobs...bgX...fgX...nohup

'top'
'top'isagoodcommandtousewhenyouwanttoseewhatyoursystem'sdoing.'top' is designed to show you how your CPU is being used. It will give you a pretty completelistofeverythingthat'sgoingoninyourcomputer.Here'sasampleoutputof the'top'command:
9:09am up4min 2users loadaverage: 0.12 0.13 0.06

71

34processes: CPUstates: Mem:62972Kav

31sleeping 11.1%user

3running 0.7%system

0zombie 0.0%nice 22672Kshrd

0stopped 88.4%idle 5312Kbuff

50420Kused 12552Kfree

Swap:1020116Kav 3152Kused 1016964Kfree 27536Kcached PID 332 350 386 345 1 2 3 4 5 48 137 141 157 161 212 225 258 USER root bob bob bob root root root root root root bin root root root at root root PRI 12 4 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 NI 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 SIZE 4492 13144 768 972 168 0 0 0 0 136 300 292 512 692 304 424 580 RSS 4184 11M 768 972 168 0 0 0 0 120 296 264 508 688 276 416 548 SHARE 1480 7728 596 704 144 0 0 0 0 96 228 212 412 296 220 348 428 STAT R S R S S SW SW SW SW S S S S S S S S LIB 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 %CPU 8.3 2.7 0.5 0.1 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 %MEM 6.6 19.3 1.2 1.5 0.2 0.0 0.0 0.0 0.0 0.1 0.4 0.4 0.8 1.0 0.4 0.6 0.8 TIME 0:09 0:04 0:00 0:00 0:02 0:00 0:00 0:00 0:00 0:00 0:00 0:00 0:00 0:00 0:00 0:00 0:00 COMMAND X netscape top FvwmButtons init kflushd kpiod kswapd md_thread update portmap rpc.ugidd syslogd klogd atd inetd lpd

72

Lesson Thirteen
File systems in Linux
Thisisabeginner'scourseandoneoftheconceptsthatnewcomerstoLinuxfind differentistheideaofafilesysteminLinux.Thatistosay,thewaydataisstoredand managedinLinux. MSWindowsandMacusersareusedtoclickingonaniconsanddraggingthefiles theywantcopiedtoafloppyoranotherpartoftheharddrive.Linuxusersthatuse KDEorGNOMEcanalsocopyfilesinthatwaytodifferentpartsoftheharddrive. However,ifyouwouldliketousefloppies,weshouldtalkhereabitaboutthetypeof filesystemLinuxuses. MSWindows,fromWindows95onupusesafilesystemcalled'vfat'.Linuxusesa differentsystemcalled'ext2'.Therearealsoothertypesoffilesystemsoutthere.You mayhavechosentohavebothWindowsandLinuxinstalledinyourcomputer.Atone point,youmighthavetoaccessfilesintheWindowspartitionofyourharddrive.You woulduseacommandcalled'mount'todothat.Youwouldalsohavetoindicateasan option in that command that the file system you want to access or "mount" is a Windows'vfat'filesystem. Onthesameidea,thoughfloppiesarebecomingsomewhatobsolete,youmaywantto storesomefilesonafloppyoraccessdataonafloppythatsomeonehasgiventoyou. Youwouldalsohavetousethecommand'mount'beforeyoucopieddatatoorgot datafromafloppydisk.IfthatpersonisaWindowsuser,thenyouwouldhaveto indicateonceagainthatthefilesystemis'vfat'.Ifyouwanttocopydatafromyour Linuxpartitiontoafloppy,youwouldhavetoformatandthen"mount"thefloppyas aLinux'ext2'filesystem.

Formatting a floppy for Linux


MostfloppiessoldonthemarketarepreformattedforMSWindows.Youcancopy datafromLinuxtoaWindowsformattedfloppywithnoproblem.Ifyouwanttocopy LinuxfilestoafloppytobeusedinanotherLinuxmachineortobeusedbyyoulater inLinux,thenitmightbebettertoformatthefloppyforLinux'sext2filesystem. Weshouldalsosaynowthatthisisconsideredanadministrationtask.Youhavetobe workingas'root'tobedoingthis.AsyougetmorefamiliarwithLinux,youcanuse commandssuchas'su'todotheworkofrootoncertainoccasionswhenyou'renot actuallyworkingasroot.We'llexplainthiscommandinlaterlessons.

73

Tocreatealinuxfloppy"byhand",youwouldplaceafloppyinthedriveandtype: mke2fs /dev/fd0 Thecommandisanabbreviatedwayofsaying"makeanext2filesystem".Theother partisthedevice,yourfloppydrive,whichisknowntoLinuxas"fd0"(floppydrive 0).Aswementionedinthefirstpartofthecourse,everythingisafileinLinux, includingyourfloppydrive. Youwillhearthecustomarynoiseofthefloppydrive(somearelouderthanothers someolderonesthatI'veheardsoundlikeachainsaw)andyouwillgetsomeoutput likethis:
Linux ext2 filesystem format

andsomeotherinformationaboutthesizeofthefloppyetc. YounowhaveaLinuxformattedfloppy.Youmaywanttorunthiscommandtocheck ifthefloppyhasdefects e2fsck /dev/fd0 Somewindowsmanagershaveaniceprogramstodoboththeformattingandthe checkingofthediskatthesametime.

Mounting file systems


Inthispartofthelessonaboutfilesystemswe'lllearnhowtousethecommands mountandumount. We've mentioned previously that there's a different idea in Linux as to what constitutesafloppydiskdrive,aCDROMdriveandanotherpartitionofyourhard disk (the Windows partition, for example). Though some windows managers for Linuxhaveprovisionsforclickingonanicontoaccessafloppydrive,forexample, themethodbehindthisisquitedifferentfromotherOSes.InLinuxthefloppydriveor otherdevicemustbe"mounted".Thatmeansbasically,incorporatingittemporarily intoyourLinuxfilesystemor,inotherwords,tellingLinuxthatitisafiletobe writtentoorcopiedfrom. To access a floppy disk from the command line of our shell, we would use the commandmountandtypethefollowing:(remember:youneedtobeworkingas'root' todothis) mount -t ext2 /dev/fd0 /floppy Nowthisassumesacoupleofthings: youhaveafloppydiskinthedrive(you'dbesurprisedhowmanytimesI forgettoactuallyputthefloppyinthedrive) in this example, the floppy type (indicated by the option t) is a Linux formattedfloppy.IfyouwanttomountaWindowsfloppy,changetheoption totvfat inyourrootdirectory(youcangettoitbytyping:cd/),youhaveadirectory called floppy.Ifyoudon't,youshouldcreateit(mkdirfloppy).SomeLinux 74

distributions createthis automaticallyduringtheinstallationprocess. Some don't. Let'sexplainwhatwe'vejustdonehere.Whenwetyped: mounttext2/dev/fd0/ floppy we told Linux that our floppy disk is now part of our Linux file system (/dev/fd0)andthatanyfileswewouldliketostoreonthatdiskwillbecopiedto/ floppy,asifitwerejustanotherdirectoryonourLinuxsystem.Ifyoudiditright, typing thecommand'df'(thecommandtoseehowmuchfreediskspace)should includesomethinglikethis: /dev/fd0 1390 649 669 49% /floppy Yournumbersmayvary(especiallyifyourfloppyisblank!) Now,tocopytoandfromthefloppydisk,youwouldtype: cp my_file /floppy Ifyouwantedtocreateindividualsubdirectoriesonthefloppy,youwouldfirstchange tothe/floppydirectory: cd /floppy Thenyouwouldusethemkdircommandtocreatethedirectoriesyouwant.Youcan also use the command cp r my_directory/ /floppy to copy the directory automaticallytothefloppy.(makesureyouhavespace!Ihaveonoccasiontriedto copya3MBfiletoa1MBfloppy!)

Mounting other devices


Youcanalsousethemountcommandtocopytoandfromotherdevices. IfyouwouldliketogetsomefilesfromaCDROM,thestandardcommandtodothis is: mounttiso9660/dev/hdb/cdrom Thetype,iso9660isthestandardfilesystemforaCD.Thedevice(/dev/hdb)isthe nonSCSItypeofCDROMandthemountpoint(/cdrom)shouldexist.Ifitdoesn't, youshouldcreateitintherootdirectorywith'mkdir',justasyoumayhavedonewith the/floppydirectory. RememberthattheconceptofCDROMisreadonly.Youwon'tbeabletowriteto thistypeofCDROMdrive.Amessagewilltellyouthatwhenyoumountthistypeof device.

Mounting another partition of the hard disk


ManypeoplemayhavepreferredtoinstallLinuxalongwithanotheroperatingsystem. YoumayhaveLinuxandWindowsinstalledinthesamecomputer.Ifyouwouldlike toaccessfilesontheWindowspartitionyouwouldtypethefollowingcommand: mount -t vfat /dev/hda1 /mnt

75

Windowsisalwaysintheprimarypartition,sothat'swhywe'veusedthedevice/hda1 (harddiskpartition1).Thechoicefor/mntisthestandardmountpointinthiscase. Youmayusethe/mntdirectorytomounttheotherdevices(floppies,CDs)aswell.I usethedifferentemptydirectories(/floppy/cdrom/mnt)toavoidconfusion. If you change to the mount directory (cd /mnt) and then type: ls and you'll see something interesting. The directories are blue but the files are green (or red depending on your distribution of Linux). You won't have the various color combinations as you do in Linux. That's because Windows' file system doesn't distinguishfiletypes.Everythinglookslikeit'saprogram(binary)insteadofaregular file. WhenyoucopyfilesfromtheWindowspartitiontotheLinuxpartitionyoushould bearthisinmind.Forexample,ifyouwantedtocopyanmp3filefromtheWindows partitiontotheLinuxpartitiontotestoutyoursoundconfiguration,itwouldshowup asaexecutableprogramandnotjustastandardfileunderLinux.Thisdoesn'teffect yourplayingit,butforamoreaccurateaccountingofwhatyouhaveonyoursystem, youmaywanttochangethepermissionsofthefilesothatitshowsupasaregularfile inyourcolorscheme.We'lltalkaboutfilepermissionsandandmakingchangesto themshortly.

Umount command - umounting file system


Mountingfilesystemsthataren'tpartofthestandardLinuxsystemisconsidereda temporaryconditioninLinux.Nowthatweknowhowtomounttheseoutsidefile systemsinLinux,theimportantthingnowistolearnhowtounmountitwhenwe're finishedusingit. IntheearlydaysofLinux,youcoulddoseriousdamagetoyoursystemifyoudidn't unmountmanuallyafteryouwerefinished.Nowadaysifyouhavemountedasystem andyoushutdownthecomputerwithoutunmounting,thechancesareprettyslimthat you'regoingtotrashafilesystem.Slim,however,isn'tgoodenoughforme.I'drather nottakeachance.Ialwaystakethetimetounmounttheseexternalfilesystemswhen I'mfinishedwiththem. Thecommandforthisis: umount [/mount point] IntheexamplesIusedinthislesson,themountpointswere: floppy:/floppythereforeumount/floppy CD:/cdromumount/cdrom Windowspartitionumount/mnt RememberalsotoNOTbeaccessingthefloppyetc.whenyouuseumountoritwill giveyoua drivebusy message.Ifyougetthis,youmayhaveleftaterminalopen whereyouwereusingtocopyorwritetotheparticulardrive.Checkyourterminalsif yougetthiserror. 76

Ijustwantedtopointoutanotherthingtoo.Youare'unmounting'butthecommandis umount (thatis,withoutthe N of un)Being u(n)familiarwiththemountconcept whenIstartedwithLinux,Ityped unmount insteadof umount andmuchtomy surprise, I got the message: command not found. U(n)deniably, I had done somethingwrong.Ittookmeawhiletofigureoutthatthecommanddidn'tincludean N.Ihaven'treallydoneasurveyonhowmanypeoplehaveactuallydonethis.Forall Iknow,Imaybetheonlypersonwhohas,butIjustthoughtitbesttowarnyou. Well,nowyoucanusethestandarddevicesthatmostPCusersneed.Laterinour advancedclasswe'lltalkaboutinstallingandusingotherdeviceslikescanners,CD writers,Zipdrivesandmatter/antimatterflowinducers.(well,maybewe'llsavethat lastoneforthesuperadvancedclasses!)

/etc/fstab
/etc/fstab.........

77

Lesson Fourteen
Shell scripts
................

The '.bashrc' file


Beforeyoustartusingthe'bash'shellyoushouldbeawareofafilethatsitsinyour homedirectorycalled'.bashrc'.You'llfindalotoffilesonthesystemthatendin'rc'. Thosefilesallowyoutoconfigureacertainprogramtorunjustthewayyoulikeit. Thebestwaytofinditistotype: 'ls .bashrc' (lslistsfiles). Youcanopenthatfilewithvi,joeorpico,aswetalkedaboutinthelastlesson.For example,inyourhomedirectoryyouwouldtype'pico.bashrc'

Adding aliases to the .bashrc file


Well,younowhave'.bashrc'openin'pico'oryournew,favoritetexteditor.Itwould beagoodideatoaddthislinefirst,soyouknowwhatyou'vedone. # my personal aliases Thepoundsign(#)tellstheshellnottoreadthatline.It'sknownasa'comment'.Then youwouldadd: cp='cp -v -i' onthenextlinewrite: rm='rm -i' sowedon'tsendanythingintobyteheavenwithoutawarning.Andfinally mv='mv -i' Soyou'realiaseswilllooklikethis # my personal aliases alias cp='cp -v -i' alias rm='rm -i' alias mv='mv -i' Save that file and logout and login again. Now you have a safer, easier shell environment.AsyougetmoreproficientatLinux,youcanaddmorealiasesasyou seefit. Nowyourshell'sreadytogo.Ifyoutypelogoutandthenloginagain,you'realiases willwork.Thereisalsoashortcut.Ifyoutype: 78

source .bashrc you'realiaseswillbereadytogo.

79

Lesson Fifteen
Backing up your files
Let'sfaceit,computersaren'tperfect.Linuxisan"almostperfect"operatingsystem, butthingsdohappenanddataissometimeslost.Thebestwaytoavoidproblemsisto backupyourfiles.Linuxprovidestwokeyprogramstodothis:'tar'and'gzip' Firstwe'llstartwith'tar'.Thisprogramsassemblesvariousfilesintoonepackage, commonlycalleda"tarball".Let'ssayyouhavesomefilesnotesthatyou'vetaken duringthiscourse.Youhave: notes_1.txt notes_2.txt notes_3.txt notes_4.txt notes_5.txt andyou'veplacedtheminadirectorycalled/linux_course.Youwanttobackthemup andkeepthemonafloppy,let's say.Youwouldtypethefollowingcommandto packagetheminatarball. tar -cvf linux_notes.tar notes*.txt First,youhavetar,thenameoftheprogram.Thenyouhavetheoptions,c(create) v(verboseshowwhatfilestheyare)(ffilemakeafileshouldalwaysbethe lastoption)Thenyouhavethenameofthefileyouwanttocreate(linux_notes.tar) andthefilesyouwanttobackup(notes*.tar). Thispresupposesthatyoumayhaveotherfilesinthedirectorythatyoudon'twantto include.IfyouwanttoincludeALLfilesinadirectory,justsubstitutenotes*.txtfor *.*. Ifyou'vegotgooddatastoragecapabilities(JazorZipdrives,aCDwriteroratape backup drive), you might want to back up whole directories along with their corresponding subdirectories. Then you would enter in the directory, let's say / home/bob/andissuethecommand: tar -cvf bob_backup.tar * Withoneasterisk,youwillincludedirectoriesandfileswithoutextensions(my_file asopposedtomy_file.txt).Bepreparedtogetafairlyvoluminoustarball.

80

Thisisthefirststepinthebackupprocess.Nowlet'slookatthesecondstep;the compressionofthesefiles.

Using 'gzip'
Aswementioned,'tar'justassemblesthefilestogetherintoonlyonefile.Thereisno reductioninthesizeofthesefiles(thetarballmightevenbebigger!)Nowwewould havetodoonemorethinginordertoreducethisfileintoamoremanageablesize:use 'gzip'. gzipisthepreferredcompressiontoolforLinux.Toreducethesizeofyourtarfile, youwouldissuethefollowingcommand: gzip your_tar_file.tar andthetarfilewouldbecompressed.Youcanalsocompressaregularfileusingthe samecommand,butgzipisusedprimarilywithtarballs. Theresultwouldbeafilelikethis:your_tar_file.tar.gz Thetwofileextensionsshowusthatthefileisatarballanditiscompressedwiththe 'gzip'format.Youcannowproceedtostorethisasyouseefit.

Putting it all together


'tar'hasanoptionbuiltintoittouse'gzip'tozipthefileatthesametimeyoumakethe tarball.Ifyouaddztotheoptions,andchangethenameofthefiletocreatetoa.gz extension,youhavethewholeshebanginonestep.Ourpreviousexamplewouldbe modifiedtothis: tar -czvf bob_backup.tar.gz * Rememberfshouldalwaysbethelastoption.

Untarring and unzipping files


Using'tar'and'gzip'sortofsupposesthatyou'regoingtowantto"untar"and"unzip" thesefilesatonepointoranother. Theeasiestwayfordoingthisistouse'tar'forthewholeprocess.Youwouldlocate thezippedtarballinquestionandthenaskyourselfaquestion: DidImakeany changestothefilesinsidethetarballafterImadeit?Ifyoudid,thenyou'vegotan oldtarball.Ifyouuntarreditinthesamedirectory,you'doverwritetheexistingones. Ifyouwouldlikeacopyoftheoldfile,untaritinadifferentdirectory.Ifyoudon't wanttheoldfiles,thenyoushouldmakeanewtarball.It'sprettystandardbackup practice.

81

Whenyou'vedecidedwhatyouwanttodo,toproceedwiththe"untarring",issuethis command: tar -zxvpf my_tar_file.tar.gz I'veusedmypreferredoptions.I'llexplainthem: zunzipthefilefirst xextractthefilesfromthetarball v"verbose"(i.etartellsyouwhatfilesit'sextracting) ppreservesdates,permissionsoftheoriginalfiles fusethefileinquestion(ifyoudon'tspecifythis,tarjustsortofsitsaround doingnothing) Thefilesareextractedandyouroriginaltarballispreserved(my_tar_file.tar.gz).You canalsountarthefileandthenusegzipseparately.Justleavethezoptionoutofthe previousexampleandtype: gzip -d my_tar_file.tar.gz or gunzip my_tar_file.tar.gz (gunziprunsgzipd"automagically"!) Thesecommandsaregoodifyou'vejustzippedaregularfile(notatarball).

Other compression tools


zip
MostLinuxdistributionscomewithothertoolstocompressfiles.Oneoftheseiszip, famousintheMSDOS/Windowsworld.Ifyou'replanningoncompressingfilesto givetosomeonewho(still)usestheWindowsoperatingsystem,thismightbeyour bestbet.Youcanalsouseunzip ifsomeonegivesyouafilecompressedwith'zip'. Consultthemanfile(manzip)forspecificinstructionsonusingthistool.

bzip2
ThereisalsoanothertoolthatisrapidlygainingacceptanceintheLinuxworld:bzip2. Asamatteroffact,theLinuxkernelsourcepackage,usuallycomes"bzipped".When youcompileakernel(createacustomkernelforyourselffromsource)thereisan optiontocreateabzippedkernel.Thisissupposedtobecometheofficialwayof doingitinthenearfuture,soitmaybeagoodideatogettoknow'bzip2'. Forallpracticalpurposesyouwouldusethistoolinthesamewayasyouwould'gzip'. Thecompressionfactorissupposedtobealittlebetter.Therearesomedifferencesin optionsformoreadvancedusers.Consultmanbzip2formoreinformation.

82

Lesson Sixteen
Installing New Programs
Thewayyouinstallanewprogramwilldependprimarilyontwothings: 1. Whatdistribution(version)ofLinuxareyouusing? 2. Whatistheoriginoftheprogramthatyouwanttoinstall? Let'slookatthefirstquestion:Whatdistributionareyouusing?

RPM
Ifyou'reusing RedHat oradistributionthatbasesitselfonRedHat,thenyou're goingtousethe RPM method.OKracingfansRPMdoesn'thaveanythingtodo with revolutionsperminute.Itstandsfor RedHat Package Manager.Thissystem takestheheartacheoutofinstallingprogramsunderLinux,forthemostpart.Youcan gototheRedHatwebsiteoranynumberofmirrorsandgetprogramsforLinux. Developers will almost always offer their programs in RPM format due to its popularity.IalsowanttonotethatRPMhasalsocometomeanthepackageitself(as in"IdownloadedanRPMyesterday"). Therearesomebasiccommandsyou'regoingtoneedtoknowtotakeadvantageof theRPMsystem. rpminew_program.rpm Thisinstallstheprogram(ioptionforinstall) rpmqprogram_name This "queries" your system to see if you've got a certain program installed. Let's say you hear there's a new version of the popular InternetbrowserOperaforLinuxandyoudon'tknowifyourRedHat baseddistributioninstallsthisbydefaultornot.Beforeyoudownload theRPMforOpera,youcouldtypethecommand: rpmqopera.If you do have the package installed, it would give you the version number:
opera-5.0_whatever-number

Ifyoudon'thavethepackageinstalled,youwillsee:
package opera is not installed

Ifyoudon'thaveOperainstalled,thenyoucandownloadtheirRPM andrun rpmiopera_whatever_version.rpm asrootandinstallthe program.

83

Ifyoudohavetheprograminstalledandthe rpmqoperacommand givesyouaolderversionnumberandyouwantthenewerone,thenyou havetwooptions. Oneisto"uninstall" theolderpackageandinstallanewoneinits place. Not that this is the most efficient option. I just wanted to introduceyoutotheeoptionforRPM.Thatis,togetridofaprogram that you've installed, you would type rpm e program_name. For example, if you've got Opera's beta version 7 and you've just downloadedthebetaversion8,thenyouwouldfirstdo: rpm -e opera ThisgetsridofOperafromyoursystem.Thenyouwouldtype rpm -i opera_beta8.rpm (orwhateverthepackageisactuallycalled).Thatinstallsthenew version. AsIsaid,thisis not themostefficientwaytoupdatepackages.The usualwayistousetheU(asinUpdatecommand.Youwouldtype: rpm -U opera_new_version.rpm andthatwouldinstallthenewversionandremovetheoldversionfrom yoursystem. ThosearethebasiccommandsoftheRPMinstall/updatesysteminanutshell. When you're using your windows manager, there are some very good tools for installing,updatinganduninstallingRPMsthataregraphicallybased.Youcanchoose menu options to do all that we explained before instead of having to type the commandsintheterminal.YoumaywanttolookintoprogramslikeKpackagefor KDEorGnomeRPMfortheGNOMEenviroment.Theymaymakethesetasksalot easier,especiallyifyou'rejuststartingoutintheLinuxworld.

Some words of caution on downloading RPMs


SomeofthemostpopularLinuxdistributionsbasetheirinstallandupdateprodedures onRedHat'spackagemanagementsystem.Theseinclude Mandrake and SuSE for example.BothofthesecompaniescreatetheirownRPMstobespecificallyinstalled ontheirsystems.Thatmeansifyou'reusingSuSEorMandrakeyourbestbetistogo totheirrespective"official"websitesormirrorsanddownloadtheirparticularRPM andinstallitusingtheprocedureoutlinedaboveortheirspecifictools.Youmayrun into a problem if you installed an RPM for Red Hat on a SuSE system. Certain componentsinthepackage(likedocumentationorlibraries)maygetcopiedintoa different directory than was intended for that system. Third party RPMs from reputablecompanies,liketheOperawebbrowserinmentionedabove,shouldinstall fineonanyRPMbasedsystem.Ihavesuccessfullyinstalledthispackage(thesame 84

exact RPMfile)onSuSE,MandrakeandRedHat.IevenconvertedthisRPMto Debian (.deb) package format and successfully installed it in a computer running Debian.Moreonthisconversionlaterintheshow! Justabriefsecondwordofcaution.GettinganRPMdoesn'tnecessarilymeanthat you're automatically (or "automagically") going to be able to install it. Many websitesoutthereofferRPMsfordownload.Thegoodonesusuallyincludealiston that particular RPM's page of other programs or libraries that you need in order successfully install and use the program. If you see a list a mile long of "requirements"(thoseotherprogramsandlibrariesyouneed),thenyoumightwantto askyourselfifyoureallywanttotrythatprogramout. Andhere'sjustaneditorialcommentonmypartaboutthistypeofthingaswell.The big buzz word with Linux is "free". That's fine. You can theoretically get a distributionfromtheInternetalongwithprogramsandinstallitforfree.(ie.nomoney down).Ithink,however,thattimeismoney,tousethetriteexpression.Timemightbe evenmorevaluablethanmoney.(lostmoneymightbereearnedbutnotlosttime). WhenIfirstinstalledLinuxohsomanyyearsago,updatingandinstallingstuffwasat timesafrustratingexperience.IsuggestthatnewcomerstotheLinuxworldbuy(yes, Isaidbuy)agoodboxedsetofacommercialdistributionandthenthey'llhavemore programsthantheywouldeverneed,allinstalledandworkingproperlyalongwitha manualtotellyouwhattodoincasesomethingdoesn'twork. Nowlet'slookatinstallingprogramswithDebian.

Debian Updates
TherearevariousmethodstoinstallingnewprogramsonaDebiansystem.Iliketo classifythemaccordingtoyourconnectiontype.

dpkg
Thisisthe"classic"wayofupdatingaDebiansystem.Typically,youcouldgoto Debian'swebsiteoranyoneofitsmirrorsanddownloadapackage.Thenyouwould type: dpkg -i package.deb toinstallit. Themaindrawbacktothisisthatyoumayfindapackagethatyoulikebutitmay havedependencies(ie.otherprogramsthatitneedstomakeitrun)andifyoudon't havethosepackages,thentheinstallwillfail. ThisiswhattheDebianpeoplethemselveshavetosayaboutthismethod: Manypeoplefindthisapproachmuchtootimeconsuming,since Debianevolvessoquicklytypically,adozenormorenewpackages 85

areuploadedeveryweek.Thisnumberislargerjustbeforeanew majorrelease.Todealwiththisavalanche,manypeopleprefertouse automatedprograms. Despitewhattheysay,themainadvantageofdpkg,itseemstome,isthatitiseasy forpeoplewhohavedialupconnections.Thisisbecausethealternative,automated programsthey'retalkingabout,whicharedselectandaptgetarebetterforpermanent connections(cable,xDSL,T1,T3).Let'stalkaboutthismethodofinstallingnew programswithDebian.

dselect
Whenyouusedselectyougetagraphicuserinterfaceofsorts(notunderXwindow, though)toguideyouthroughtheinstallofnewprograms. Firstyou'llgetaskedforyourpreferredaccessmethod.Thatmeans,howyou'regoing togetandinstallthem.Forexample,ifIweredoinganinstallofDebianwithCDs, thenIwouldchooseCDROM.ButifIwereupdating,IwouldchooseFTP Then youwould choose thepackagesyouwantwitha + sign.Youcanevenput updatesonhold(indicatethatyouwanttoupdate,butnotactuallydoit)witha=sign. There mayevenbeconflicts or dependency problems and'dselect' will warn you aboutthose. Thenyoustarttheprocessbychoosingtheinstalloption.Debianwillthenconfigure theinstalledpackages.Thenyou'reonyourway. As I said before, the main advantage to this is that any conflicts or dependency problemswillberesolvedrighthere.TheDebianpeoplepointoutthatthisisidealfor installsorlargescaleupgrades.Ifthat'sthecase,itseemsthataslowandsometimes expensivedialupconnectionwouldbelessthanidealforthis. Inthenextsectionwe'lllookatinstallingprogramsunderSlackware.

Installing new programs on Slackware


Slackware,knowntotheLinuxworldas"Slack",hasthereputationofbeing,onone hand,aflexibledistributionthatallowsyoutodopracticallyanythingyouwantand, ontheotherhand,onethatisfor"experienced"Linuxusersonly. Alotoftheseconsiderationsare"politically"motivated.Slackwarelackssomeofthe "smooth"and"slick"graphicinstallationpackagesthatarebecomingstandardfarein commercial companies' offerings but in the end, if you're willing to just use the commandlineutilities,it'sjustaseasilyupdatedasanyothermajordistribution.

86

Slackware's package format


Slackware packages come in *.tgz format. This avariation of the *.tar.gz format we'veseenbefore.Youcangotoyourfavoritewebsiteanddownloadnewprograms foryourSlackwaresystemandwithasimple:
installpkg some_program.tgz

youhaveyournewprograminstalled. Ifthatparticularpackagedoesn'tquitemoveyouandinspireyoutoomuch,youcan justremoveit:


removepkg some_program.tgz

Youcanalsoaddtheoptionwarnbetweentheinstallpkg/removepkgcommandand insteadofinstallingthepackage,itwilltellyouwhatnewfilesaregoingtogetadded toyourharddisk.That'sagoodoptionforthe"IwonderifIwantthis"momentsof yourlife. Youcanupgradeprogramstonewerversionswiththiscommand:


upgradepkg a_new_version_of_something.tgz

Using other package formats


Ifyou'reusingSlackwareandyoucan'tfindapackageyourlookingforinthe*.tgz format,youcanalsograbontoan*.rpmandconvertit. Thewaytodothisis:
rpm2tgz some_package.rpm

Thistakesthe"rpm"inquestionandconvertsitto*.tgzformat.Thenyoucanuse installpkgonthenewfileyou'vecreatedtoinstallit.

87

Lesson Seventeen
Automation of Tasks on Linux
Oneofthemaintasksofasystemadministratoriscarryingoutmaintenanceworkon theserver.Mostofthesetaskscanbeautomatedorprogrammedtobecarriedoutat certaintimeswithoutuserintervention.Inthissectionwe'lltalkaboutthetwomost widelyusedprogramstocarryouttasksinthisway.

Use of 'at'
'at'isaprogramtocarryoutcommandsthatyouintendtodoonlyonce.It'smostly usedforschedulingspecificjobsunderspecificcircumstances.Ifyouhadtorotate yourcompany'swebserverlogseverySaturday,'at'isnottheappropriatetoolforthe job.Thatwouldbedonebestwith'cron',aboutwhichwewilltalkaboutshortly.Let sayyourboss,theCTO,calledforameetingwithyouat1:00.Hewantstoknowhow frequentlyyourexternalconsultantsareloggingintothenetwork.Thisisaprime candidatefor'at'. First,you'dtype: at 12:45 whichwouldgiveyouplentyoftimetogetthatinformationbeforethemeeting.You willseethe'at'prompt: warning: commands will be executed using /bin/sh at > Nowyou'dwritethecommandsyouwantcarriedout.Herewe'llgettheoutputofthe commandlast,whichtellsuswho'sloggedintoourserverslately,andwriteittoafile called'logins'.Thesecondcommand,separatedbyasemicolon(;)willthenprint thatfileusinglp. last > $HOME/log-ins; lp $HOME/log-ins press'Enter'andthen'Ctl+d'andyouwillseethefollowing: job 15 at 2003-02-16 12:45 Ofcourse,yourjobnumberwillvarywiththenumberoftimesyou'veused'at'. Therearevariouswaystoindicateatwhattimeyouwant'at'tocarryoutcommands. atnow+5minuteswillcarryoutacommandfiveminutesfromwhenyoutypeit. There's even a provision for at teatime which will carry out commands at 4:00 PM/16:00hrs.(Ifyoudon'tbelieveme,consult'manat'!).Youcancancelthesejobs aswell.Ifyoutype: atrm 15 youwillremovejob15fromthe'at'queue.Toseewhatisinthe'at'queue,type: 88

atq Youcancontrolwhichusersareallowedtouse'at'.Bydefault /etc/at.deny controlswhocannotuse'at'.Thatistosay,theuserslistedinat.denycannotuseit. Youcanalsocreatean /etc/at.allow file.Creatingat.allowmakestheatdaemonignorethe/etc/at.deny.Therefore,anyone whoisnotinat.allowcannotuse'at'.Thequestionofusingonefileoranothercomes downtoaquestionofyourmanagementstyle.Ifyouprefertoletpeopleusethings untiltheyabusetheprivilege,thenusethedefaultat.deny.Whentheuser'barney' programsan'at'jobtosetoffaninfernalsoundingnoisewhenhe'sgonetogetcoffee, scaringthebejeebersoutofeverybodyintheoffice,thenyoucanaddhimtothe at.denyfile.Ifyou'reoftheopinionthatnobodyneedstouseit,thencreateanat.allow filewithonlyyourpersonaluseraccountlisted.Rememberthattherootusercan alwaysuseat.

Use of 'cron'
Fromasystemadministrator'spointofview,thecrondaemonisprobablythebest thingsinceslicedbread.Youcanschedulepracticallyanyprogramatanytime,for anydateandatanyinterval.Thatistosay,ifyouwantatextdumpofthenumberof timesapersonwiththeIPaddress64.09.200.12hasloggedintoyourcomputerand youonlywantitonFebruary4th,cronwilldothisforyou. Thejobsthatyouwanttorunwithcroncanbescheduledinvariousways.Themost commonwayistoeditafilewhichisknownasyourcrontab.Normally,eachuserhas his/herownandisabletoschedulejobsbyeditingit.Youcanaddtoanddelete entriesfromyoucrontabbytyping: crontab -e Butbeforewegojumpingrightintoschedulingjobs,it'simportanttopointoutthat cronlooksforaparticularsyntaxinyourcrontabfile.Youjustcan'tjustwrite: get my mail from mail.mydomain.com andexpectittowork. Onceyouhavedecidedwhenyouwantaparticularcommandtoberun,youaddthe commanditselfattheend.Atypicalcrontabentrywillenduplookinglikethis: 30 3 * * 0 $HOME/bkup_script which runsascriptinyourhomedirectorytobackupyourfiles at 3:30AMon Sunday. Thesyntaxinyourcrontabisnoteasytomaster,butitisnotexcessivelydifficultto comprehendeither.First,thereare5timeperiodsthatcronlooksfor.Youstartyour crontabentrywiththese.Hereistheorderandsomeexamples:

89

Minute 15=quarter past 40=twentyto

Hour 18=6:00PM 2=2:00AM

Day(ofthe month)

Month

Weekday 0=Sunday 6=Saturday

12=12thdayof 4=April themonth

9=9thdayof 10=October themonth Table1.GuidetoCrontimes

Ifyouenteredthisintoyourcrontab,youwouldsimplysavethefilebypressingESC +:wqwhichisavicommand.Viisnormallytheeditorthatcrontabusesbydefault, but youmayuseatexteditorother thanvi,bytypingexport VISUAL=pico,for example,whichwouldallowyoutousethepicoeditor.Everytimeyouwanttoalter, addordeleteanentry,youwouldfirsttype. Youwillnotbeabletouseallofthesefieldsatthesametime.Ifyouhaveusedthe firstfour,youdonotneedthelastone.Thislastone,theweekday,isparticularly usefulbecauseitletsyourunjobsonceaweek.Thereisalsoanotherwayofdoing that andwe'll talk aboutitshortly. Ifyoudon't wish to specifyaparticular time period,youmustsubstituteanasterisk(*). crontab -e Enterwhateveritisthatyouwanttogetdoneandthentype ESC + :wq (orthecombinationofkeysusedtosaveafileinyourparticulartexteditorofchoice). Ifyou'recuriousaboutwhat'sinyourcrontabfileandwanttolistthejobsyouhave programmed,type: crontab -l Ifyouwanttodeleteyourcrontabfile,type crontab -r

Variations on a theme
Crontabentriesdon'thavetonecessarilyhavejustnumbersinthem.Wecancombine the numbers with other characters to modify how commands get carriedout. For example,IhaveaUSBwebcamthatdoesn'treallydowhatit'ssupposedto,whichis totakeapictureeveryminuteandthenshutoff.Ittakesthepictureallright,butit doesn'tshutoff.SoIwroteascripttoshutitoffandthenIaddedacrontabentryto callthisscripteveryminute.ThisiswhatIadded: 0-59/1 * * * * $HOME/shutoff_cam >/dev/null 2>&1 Let'slookatthisonepartatatime 059/1 basically means that between the 059 minutes of every hour, at every 1 minute interval,thecameraistoshutoff.Toshowyouhowusefulcronis,Irememberseeing aJamesBondmoviewheretheperpetualbadguy,Blofeld,wasbrainwashinggirlsto

90

carry out biological attacks from a base in the Swiss Alps. He would play these hypnotictapestothegirlseveryevening.ThereisonescenewhereyouseeBlofeld andoneofhisminionsswitchingthetapesmanually.IfonlytheyhadhadaLinux computer!Theycouldhavedonethis:
30-45/3 22 * * * >/dev/null 2>&1 mpg123 /home/esblofeld/brainwash_girls.mp3

whichwouldplaythebrainwashinginstructionsat3minuteintervalsbetween10:30 and10:45PM.
Disclaimer:PLEASEDONOTTRYBRAINWASHINGTECHNIQUESATHOME!ALSO, LINUXONLINEDOESNOTENDORSETHEWORLDDOMINATIONSCHEMESOF SPECTRE.THISISONLYUSEDASANEXAMPLE.THEONLYWORLD DOMINATIONSCHEMEWEENDORSEISTHATOFLINUSTORVALDS.

Weshouldalsopointoutsomethingthatyou'veprobablyalreadynoticedinthetwo examplesabove;thattheyendwith command >/dev/null 2>&1 Wetackedthisontheendbecausecron,bydefault,mailsa"report"toyouofthe commandyoucarriedout.Thisissoyoucaneithergettheoutputdirectlyinthemail, and/ortoseeifthecommandwassuccessful.Youmayhavemadeamistakewhen youaddedanentrytoyourcrontab(liketypingthewrongpathorthenameofa commandwrong).Thatway,you'renotifiedandevenifyourjobwasimportantand youmissedthefirstone,youcancorrectitandthenyouwon'tmissanyothers.Again, intheexamplesabove,ifwegotamaileverytimethecommandwascarriedout (everyminuteorcoupleofminutes),yourinboxwouldquicklyfillupwithuseless mail.Therefore,wetackthatonsothatcronwillsendnotificationofthosejobsto/ dev/null(ie.thetrash). Herearesomeotherexamplesofvariations:
0 0 15,30 * * cat /var/log/mysql.log > $HOME/mysql_use 30 8 * * 1-5 /usr/bin/who

Thefirstonemakesuseofthecomma,whichmeans'and'.Inthefirstexample,wesee thatwewillgetareportofMySQLuseonthe15thand30thofeverymonth(except February,ofcourse!).Thesecondonewillrun'who'whichtelluswhoisloggedin, everyweekday(15)at8:30AM.Thiswouldbeaparticularlygoodoneforsystems administratorswhowanttoseewho'sworking(oratleastwho'sloggedin)atthetime theyalsostartwork.

Permissions for cron


Theabilitytousecronisregulatedinthesamewayas'at'.Thosein /etc/cron.deny arenotallowedtousecronandallotherusersareallowed.Ifyouhavea /etc/cron.allow

91

file,thissupersedescron.deny(ie,cron.denyisignored)andallowsonlythoselisted inittousecron.

cron.hourly, cron.daily and cron.monthly


MostLinuxdistributionshavethreedirectoriesin/etccalledcron.hourly,cron.daily and cron.monthly, which, as you may have already guessed, lets the systems administratorrunjobsonanhourly,dailyormonthlybasis.Simplybyplacingashell script here,jobscanbecarriedoutatthoseintervals.Thereisnoneedtohavea crontabentryforthesejobs. Asyoucansee,theskyisthelimitwiththethingsthatyoucandowithcron.Itwon't getyoutothepointwhereyou'veprogrammedabsolutelyeverything,lettingyoupass yourworkinghoursatthebeach,butitwillmakeyourlifeawholelotsimpler.

92

Lesson Eighteen
Networking
ifconfig and route
......

Other config files


Themostimportantconfigurationfilesarelocatedinthe/etcdirectory.Anygood administratorwillknowthisdirectorylikethebackofhis/herhand.Hereislistofthe mostimportantfilesthatyoumayhavetochangeregularly: hosts hosts.allow hosts.deny Let'shavealookatwhatthesefilesdo. hosts isalistofthemachinesinyournetworkwiththeirnamesandIPaddresses. Anytime you add a new machine to the network, you should add an entry here. Actually,beforetheDomainNameSystem(DNS),thereusedtobea"master"hosts filetolocateallofthemachinesontheInternet.Thiswas,ofcourse,inthedays beforetheInternetwasusedbythegeneralpublic.Itlookslikethis:
# this machine 127.0.0.1 localhost

# other hosts in the local network 192.168.0.1 enterprise.mycompany.com 192.168.0.2 constellation.mycompany.com 192.168.0.3 intrepid.mycompany.com 192.168.0.4 exeter.mycompany.com 192.168.0.5 router.mycompany.com

enterprise constellation intrepid exeter router

Thenamingschemeisentirelyuptoyou.WhatwehavehereisaclassCnetwork (192.168.X.X)whichisconnectedtotheInternet,probablyviasomehighspeedline. Thefirstpart,asyoucansee,aretheIPaddresses.ThisisfollowedbytheFully QualifiedHostName,whichincludesthedomainnameandthetopleveldomain.You shouldnotuse.com,.orgorotherInternettopleveldomainsifyou'renotconnectedto theInternet.Thelastpartisthenameofthemachineor"alias".Thefirstlineofthis hosts file lacks that last bit. That's because you can enable what's known as 'loopbacking'onaLinuxmachine.Itmaybethecasethatyouwanttorunnetworking 93

programsonamachinebutyoudon'thaveanactualnetwork.Thinkof127.0.0.1asa virtualnetworkinsideyourmachine.Whenyoutype127.0.0.1orlocalhost,it"loops back" to the machine itself. Even with a network, this is often used to run developmentwebservers,forexample,whereyouwanttorestrictaccessfromthe outside. hosts.allow isafilethatcontrolswhohasaccesstotheservicesthatyourmachine provides.Itmightlooksomethinglikethis:
ALL : 192.168. imapd: .friendly.com, 999.99. sshd: .friendly.com

Thesyntaxissimple.Youdefinetheservice(all,imapd,sshd)andseparatethelistof hostsallowedtousethemwithacolon(:).ThehostnamesorIPaddressesmustbe separated by commas. Neither names nor numbers have to be complete but they shouldbeginorendwithadot(.)whereapplicable.Thatis,intheexampleabove, hostnamescanbeginwithadotbecausethatmeansanymachineinthatdomain, friendly.com,canaccessthatservice.(ie,quite.friendly.com,very.friendly.com).With numbers,youcanspecifythatmachinenetblockareallowedtoaccessyourservices byputtingadotafterthefirstsetsofnumbers,asyoucanseeinourexampleof 192.168.and999.99 Inthisexample,thoseusingmachinesinyourlocalnetwork(192.168.)areallowedto use all the services available (ALL). Machines in domain .friendly.com and the netblock999.99.areallowedtoaccesstheIMAPdaemon,normallyusedtoaccess emailviaIMAP..friendly.comisallowedtologintoournetworkviaSSH(Secure Shell). hosts.deny isafilethatcontrolswhocannotaccesstheservicesthatyourmachine provides.Mosthosts.denyfilesarethesame.Theylooklikethis:
ALL : ALL

whichmeansthatALLaredeniedALLservices.Thisisstandardpractice.Aswehave seenwithcronandat,X.denyandX.allowfilesworkontheprinciplethatuserswho arenotspecificallyallowedtouseservicesaredeniedthem.Thoughitmaysound logical,itneedstoberestatedthatifweusethehosts.denyapproach,ifyournameis not listed, then you're allowed to use all the services offered. If we used the hosts.allowapproach,thenweestablishwhocanusecertainservicesandwetherefore denytheresttoeverybodyelse.Thisiseasiertomaintainanditismoresecure. Anotherconfigurationfilethatyoumaycomeincontactwithfromtimetotimeis resolv.conf. resolv.confisusedprimarilytolistthenameserversyourmachineusestofindother machinesontheInternet:
search mycompany.com

94

domain mycompany.com nameserver 192.168.0.3 nameserver 999.99.9.9 nameserver 999.99.9.8

Thefirstentries,searchanddomain,tellswhatdomainstolookatandthenappendto names. For example, if you just typed the name 'intrepid' in a browser, it would append .mycompany.com to that name to access that machine. The other entries beginningwithnameserverlistthetheIPaddressofmachinesthathaverunDomain Name Service (DNS) software (BIND, for example) so that you can find other machinesonthe Internetbyname.Ourfirstentryhereisamachineinourlocal networkthatrunsthissoftware.TheotherslistedarenormallythoseofyourInternet serviceproviderorotherswhooffernameservicetothepublic.

Ping, traceroute, ssh, netcat.....


.......

95

Lesson Twenty
Compiling kernel
What is the Linux kernel
TheLinuxkernelisessentiallywhatLinusTorvaldsstartedworkonin1991.Akernel isthepartoftheoperatingsystemthathandlesthecommunicationbetweensoftware andyourmachine'shardware.InthedecadesinceLinusfirstkernelwasreleased,its complexityhasgrownenormouslyandsohasthenumberofpeopleworkingonit.It isnowthelargestcollaborativeprojectintheworld.Thereasonforthisisbecause LinusreleasedtheLinuxkernelunderthetermsoftheGNUGeneralPublicLicense, whichmakesitfreelydistributableandallowsanyonetomakechangestoit.Inthis lessonwearenotgoingtobetalkingaboutmakingchangestothesourcecodeitself, butwewilltalkaboutchoosingcertainfilesofthissourcecodeinordertocreatea customkernel.

Where to get the kernel source


AsImentioned,thekernelsourcecodeisavailableforanyonetodownloaditandyou canfinditatKernelOrg. Atthetimeofthis writing, thelateststableversionoftheLinuxkernelis 2.4.22.Thoughthearrivalofversion2.6isimminent,wewillbedealingwith the2.4.Xversionofthekernelinthislesson. Thelateststableversionofthekernelcomesinatjustunder30megabytesinabzip'd tarball.Agzip'dversionisalsoavailableandisslightlylarger.Youshoulddownload theformatofyourchoiceanduntaritinthedirectory/usr/src/.

Kernel configuration
Compilinganewkernelisaseriousthing.It'salotlikechangingthemotorinyour car.Ifyouhaven'tdoneitcorrectly,themachine,whichislikeyourwholecar,will notrun.Forthisreason,youshouldnotattemptthisonamissioncriticalsystemthe firsttimearound.Ontheotherhand,youshouldn'tbeafraidofiteither.Likeany upgrade, if you have taken the appropriate steps and have made backups you shouldn'thaveanyproblems.

96

First,youneedtoknowwhathardwareisinyourmachineinordertogetagood kernelattheendoftheprocess.Therearealsootherconcerns.Forexample,youneed todecidewhatkindsoffilesystemsyourmachineneedstoworkwith(ext2,Reiser, VFAT,NTFS,etc),whatcharactersupporttoincludeinthekernel,whatnetworking protocolsyouneedtouseorwhetherthemachinewillbeusedasarouterorfirewall, tonameafew.ThisisimportantbecausewhatsetsaLinuxkernelapartfrom,say,a MicrosoftWindowsoneisthatyoucanpickandchoosewhatgoesintoitandthen yourkernelwillbemuchleaner.ThiscustomizationiswhatmakesLinuxoperating systemsmorestable.Soit'simportanttoknowwhatyouneed.Itmakesnosenseto compilesupportforUSBscannersintoyourkernelifyou'renotgoingtobeusinga USBscanner.Ontheotherhand,ifyouhavethistypescannerandyoudon'tcompile USBsupportintothekernel,youwon'tbeabletouseit. Therearethreemaininterfacesthatyoucanchoosefromwhenyouarepreparingthe configurationofanewkernel.Theyare'config','menuconfig'and'xconfig'.Thefirst one is an oldstyle commandline interface that is not very attractive nor do I recommend it if this is something that you've never done before. The last one, xconfig,isaGUIbasedconfigurationtoolthatrequiresyouhaveXwindowrunning. Thismaynotbethebestoptionifyouhaveaserverbecausethere'snoneedtobe runningxwindowinthatenvironment.Asageneralrule,Istickwiththemiddle option,'menuconfig'becauseithasanncursesbasedGUI(textmodewithcolors)and thereforeitisvisualandstraightforward.Itcanalsobeusedtoconfigureakernelona remote machine, something that xconfig is just not suited to. Here's what the menuconfigsystemlookslike:

Tousethis,justtype:'makemenuconfig'insideyour/usr/src/linux/directory.You willseesomethingverysimilartothescreenshotabove.Whatyouhaveherearethe major categories of kernel configuration options. Since I don't know what each machineoutthereisgoingtoneed,itwouldbeimpossibletogoovereveryoption. However,we'lllookatthemorecommonoptionsandusethoseasexamples. 97

Thekernelconfigurationprocesscreatesa.config([dot]config)filewithyour options in the /usr/src/linux/ directory. If you have systems with similar hardware,youcanuseitbetweenmachines.Thisalsocomesinhandyifyou doacompleteswitchtoanotherdistribution,forexample.Ifyouusethesame. config, you'll need to fire up 'menuconfig' once so your .config file gets "registered"withthenewsystem.

Using kernel modules


OneofthemostpopularfeaturesoftheLinuxkernelisitssupportformodules.A moduleiscodethatprovidesforsupportforcertainthings.Thesemodulescanbe insertedorremovedfromakernelwhileitsrunning.Normally,supportfor,say,a networkcardwouldbebuiltintothekernel.Thatis,thekernelwouldalwaysinclude thatsupport.Itwouldformpartofthekernelitself.Ifyournetworkcardweretofailat some point and you weren't able to find that kind of card, you would have to recompileyourkerneltogetittoprovidesupport.However,ifyouindicatedthatyou wantedtoprovidesupportforvarioustypesofnetworkcardsasmoduleswhenyou configure your kernel, you could swap out a new card supported by one of the modules.Youwouldthenhaveaprogramcalled'insmod'activatethemodulesto providesupport.Besidesthis,akernelwithallofitssupportoptionscompiledintoit willbebigger.Itmaybecomesobigthatyoumaynotbeabletomakeafloppyrescue diskfromit.It'sperhapsagoodideatoconfigurenonpermanentitemsasmodules. (SCSI supportforpendrives,ifyourhardwareisIDE,forexample).Configuring itemsasmodulesrequiresyoutochoosethisoptionatthebeginning. Loadable module support --->

Ifyouactivatethis,youshouldindicate(M)ifyouwantsomethingconfiguredasa module.Anasterisk(*)willcompilesupportdirectlyintothekernel.

Other kernel options


Directlyfollowingthemodulessupportoptionsistheprocessortypeoption. Processor type and features ---> Here,youshouldusetheprocessortypeforyourmachine(PentiumIII,AMD,etc.). YoushouldobviouslynottrytogetsupportforanAMDAthlonifwhatyouhaveis anIntel486.Again,youneedtoknowwhat'sinyourmachinebeforeyouevenstart. Youwillfindtherestoftheoptionstofairlyselfexplanatory.Ifyou'regoingtobe using themachineas amailserverand/orwebserver,youneedsupportforyour networkcard,tcp/ipsupportandperhapssomeotherprotocolsplusiptablessupportis recommmendedifyou'replanningonimplementingafirewall.Choosingsupportfor things like this then leads to opening subcategories to see more options for this 98

support.Again,it'simpossibletogothroughalloftheseoptions,butfortunatelythe kernelmaintainershavedonealotofworktoprovideexplanationsformostofthem. They are to be commended for their labors. By pressing < Help >, you'll see explanations and even some recommendations. If you think you might need this support, it's agoodidea toread through theexplanations thoroughly. Andasthe kernelmaintainerspointoutinallofthesehelpbits,ifyoudon'tknowwhatthis means,youcanprobablysafelychoose'no'. If you're planning on "rolling your own" kernel, as they say in the Linux community,pleasetakethenecessarytimetodothiscarefully.Napoleononce said:'Dressmeslowly,I'minahurry'.Thetimeyoutakeatthebeginningto makesurethatyou'veincludedallthefeaturesyouwantwillsaveyoutimeon theotherend,justasNapoleonknewthatthetimespentinmakingsurethe buttons were all lined up prevented his dresser from having to unfasten everythingandstartagain.IhavebeeninsituationswhereIrushedthrougha kernelconfigurationonlytobootthemachineandhavesoundcardsnotwork orfirewallsgiveerrormessagesjustbecauseIleftthingsoutinmyhaste. Whenyouexit'menuconfig'youwillbepromptedtosaveyourconfiguration.Once you'vedonethis,youcanproceedtocompileyournewkernel.

Compiling a new kernel


Irememberthedayswhencompilingthekerneltookhours(orevendaysonslow machines).Withtoday'spowerfulCPUsandcheapmemory,youshouldprobablybe able to get a new kernel up and running in under a half an hour (not including configurationtime). Your first step in compiling the kernel will be to create the interdependency configurationforthenewkernel.Forexample,ifyou'vegotaBTTVwebcamyou alsoneedvideosupportforLinux.Ifyou'vechosenBTTVsupportforyourkerneland not'VideoforLinux',thenyourdependencieswillbreak.Tomakesureyou'vegot everythingyouneed,youneedtotypethefollowing: make dep You'llstartseeingalotofactivity.Ifyouseeerrormessagesattheend,thenyou've gotsomeunresolveddependency.You'llneedtogobackto'menuconfig'andadd support according to what the error messages show. If this isn't your first try at buildingthekernel,youcaninvoke thefollowingcommand tocleanupfilesleft behindfrompreviousattempts.Itisoptional. make clean Nowwe'rereadytocreateourkernel.Youcannowinvokethefollowingcommandto compileyournewkernel: make bzImage

99

Again,ifyou'reworkingwithrecenthardware,thiswillnottaketoolong.Ifyou're curious,youcanwatchwhatit'sdoing.Ifyou'vegotaslowmachineandyou'renot wellversedinCprogramming,itmightseemlikewatchingpaintdry.Soonerorlater you'llhaveanicenewkernel,depositedin/usr/src/linux/arch/i386/boot/.Thisdoesn't meanthatyou'refinished,however.Ifwe'vechosentousekernelmodules,weneedto dealwiththosenow.Weneedtodothis: make modules Thiscommandwillcreatethemodules.Nowyoumustmovethemto/lib/modules.To tothis,youneedtousethiscommand: make modules_install Pleasenotethatthere'sanunderscore(_)betweenthosewords.Eventhoughthat'sthe last command we're going to invoke related directly to the kernel, we're still not finished. Now we need to move our new kernel to the /boot directory. This is accomplishedbysimplydoing: cp /usr/src/linux/arch/i386/boot/bzImage /boot/ If you've already got a bzImage, this will overwrite it. If you want to keep the previous kernel image, you may rename either one of the files (kernelnew, bzImage.old,etc.). Westillhaveonemoresteptogo.Weneedtotellthebootloaderaboutyournew kernel.Thiswilldifferdependingonthebootloaderyou'reusing.

LILO and GRUB


In case you're wondering, we're still talking about the kernel, not a Walt Disney movie.LILOandGRUBaren'tcartooncharacters.Theyaretwobootloadersthatare usedtobootthekernelonLinuxsystems.

LILO
LILOhastraditionallybeenthemostpopularbootloaderonLinuxsystems.Wetalked brieflyaboutLILOinoursectiononconfigurationfiles.Herewe'regoingtotalkmore indepthaboutit.LILOisaprogramthatallowsyoutochoosehowyou'regoingto bootyourcomputer.YoucanconfigureittobootoneormoreLinuxkernelsoreven boot into another operating system, like Microsoft Windows. LILO is commonly installedintothemasterbootrecordoryourharddrive,thoughyoumayalsochoose toinstallitintoasectorofaprimarypartition.Ithasaconfigurationfile,lilo.conf, whichcontrolswhatitdoes.Thiscanbefoundin/etc/lilo/.Here'sthesamplelilo.conf wesawinapreviouslesson:
# device to boot boot=/dev/hda # our root partition root=/dev/hda1 # map file map=/boot/map # delay in 10ths of a second before booting delay=20

100

# kernels to boot default=linux image=/boot/bzImage label=linux read-only append="hdc=ide-scsi" image=/boot/vmlinuz label=linux_old read-only

This is wellcommented and not tremendously difficult to understand. First, we specifywhichdevicecontainstheoperatingsystemsand/orkernelstoboot.Inthis case, it's in the first IDE hard disk of the machine. The location of the partition containingtheseisthefirstpartition,(dev/hda1).Thenwehavethereferencetothe 'map'file.Thisfilecontainsinformationaboutyourkernelthatmaybeneededby programsthataccessit.Thenextlinesaretheactualkernelstobebooted,starting withanotationwithnameofthelabelofthekernel/operatingsystemtobebootedfirst (default=linux).It'sstandardproceduretoincludealabelsothatthelilomenuyousee atboottimecanidentifythedifferentbootoptions.Kernelsaregenerallylabeledread only.Thelastiteminthefirstkernelisan'append'parameter.Inthisexample,wesee instructionstotreatanIDECDRWasaSCSIdevice.Thisisanexampleofpost kernel configuration. Even though we may have compiled SCSI support into our kernel,westillneedtotellthekerneltouseitincaseofourdriveactuallybeingIDE. Thislittletrickissomethingwecan'tcompileintoourkernel,soweneedto"append" thisbehaviorhere.Youwillalsoseethatwearechoosingbetweentwokernels.We canaddmorehereifwewant.That'swhatwe'regoingtodonow:
image=/boot/bzImage.new label=linuxnew read-only

Wemustaddtheabovelinetolilo.conftomakeoursystemawareofthenewkernel. Afterwesavethechanges,weneedtoinvokeLILOsothatthechangestakeeffect. Simplytype: lilo Thislaststepisextremelyimportant.Ifyoudon'tdothisandyoushutdownor restart,yoursystemwillnotbeabletobootfromtheharddrive.You'llneedto insertafloppyorCDrescuediskandmounttheharddiskpartitionwhere lilo.confresidesandrunliloagain. Nowyou'refreetorebootandtryoutthechanges.

GRUB
GRUBisaGNUbootloading utility.Itisnowwidelyusedinmainstream Linux distributionslikeRedHatandMandrake.Ifyou'reusingoneofthesedistributions, GRUBhasbeenconfiguredforyouduringtheinstallationprocessandlikeLILO,is 101

normallyinstalledintothemasterbootrecord.Here'smygrub.confformyRedHat workstation:
default=0 timeout=10 splashimage=(hd0,0)/boot/grub/splash.xpm.gz title Red Hat Linux (2.4.20-8) root (hd0,0) kernel /boot/vmlinuz-2.4.20-8 ro root=LABEL=/ initrd /boot/initrd-2.4.20-8.img

AswedidwithLILO,we'lladdsomelinessothatwecanuseournewkernel:
title Custom Linux Kernel 2.4.22 root (hd0,0) kernel /boot/bzImage ro root=/dev/hda1 hdc=ide-scsi

'title'iswhatwillappearinthesplashscreensothatyoucanchooseatboottime.what follows'root'ishowGRUBunderstandsyourharddrive.Linuxwillbootfromthe firstpartitionofthefirstharddrive.Thisisthehd0,0part.GRUBstartscountingat zero,thoughitmaysoundconfusingatfirst.NextwetellGRUBwherethekernel imageis,tobootitreadonly,whereourroot(/)directoryislocated.Finally,likethe LILO'append'parameter,wetellGRUBwe'vegotaIDECDRWdrivethatshouldbe treatedlikeaSCSIdevice. UnlikeLILO,wedon'tneedtotypesomethinglike grub sothatourchangesget registered.Afteryousaveyourchangesingrub.conf,youjustneedtorebootand choosethenewkernel.

Enjoy your new kernel


Nowyoucanenjoyyournewkernel.Itprobablyrunsbetterthantheonethat'soffered out of the box by most distribution vendors. Also, keep in mind that users of proprietaryoperatingsystemscan'tchangetheirkernelforbetterperformance.That's anotherreasonforenjoyingitthefreedomthatLinuxprovides.

102

oldstuff LessonSeventeen PrintingunderLinux AlthoughthisismypersonalopinionandIhavenotdonescientificresearchonthis topic,Iwouldsaythatwordprocessingisprobablythecomputeractivitywhichis donewiththemostfrequency.Emailmaybesurpassingthepopularityofbasicword processing(emailisjustanextensionofthat,really).Thefactisthatpeopleopenup theirwordprocessorofchoice(ortheonethey'reforcedtouseatwork)andwrite thingsonaprettyregularbasis.Writingthings,logically,meansprintingthem afterwards.Despitewhatwe'rehearingaboutthewebdoingawaywiththeprinted materialasweknowit,itseemsthatwehandlemorepapernotlessofitinour networkedworld.Afterall,manypeoplecurlupinbedwithanovelorareportfor work.Idon'tseethatcustombeingalteredunlesssomeonecomesupwitha comfortablewaytouseacomputerinbed! Obviously,ifwriting/wordprocessingissoimportantandprintingisthelogicalnext stepafterwriting,thengettingyourprinterupandrunningunderLinuxisgoingtobe apriority.Luckily,Linuxhaschangedagreatdealandhardwaremanufacturersgot theideaquickthatitdidn'tmatterwhatOSpeopleusedtheirprinterswith,itwasjust importantthattheyusedthem.Thatmeansthatallofthemajordistributionsofferfirst ratetoolstogetpracticallyanyprinterrunningunderLinux. Whatyou'redoingwhenyouprintunderLinux Historically,printingintheUnixplatformsstartedoffasjustsendingplaintexttoa lineprinter,(resultinginratherplainlookingtextonpaperwithholesoneachside someofyoumightrememberthis).ThebasicmeansofprintinginLinuxjusttakesoff fromthere.WhenyoufirstsetupyourLinuxmachinetouseaprinter,you'llbe configuringthelpror"lineprinter".Thelprworkswiththelpdor"lineprinter daemon"runningonyoursystem..A"daemon"isjustaprogramthatworksinthe background,withoutyourdirectintervention.Thisdaemonjustwaitstherefor printingjobstobesenttoit,whichitwillthensendtothelpqor"lineprinterqueue". Thequeue(queuetheBritishwordforwhatAmericanscalla"waitingline")justputs yourprintjobonholduntilthesystemfiguresoutthewaytoprintit.Thisholding patternisusuallyprettyquickmaybeacoupleofsecondsbecausecomputerswork prettyfast,generally. AsImentioned,printingusedtoconsistofjustsendingratherboringlookingoutput toalineprinter.Today'scomputingneedsintermsofprintingaremuchmore demanding.Exoticfonts,graphicsandothervisualgoodiescanbefoundinstandard printedmaterialthatcomesfromacomputer.YourLinuxmachineshouldbecapable ofprintinganythingyouwantaslongasyouhavethecorrectfilters.Forexample,if youdownloadedareportfromtheSavetheWhalesFoundationonthematinghabits ofthepilotwhaleinPDFformatandyouwantedtoprintit,you'llneedsomefilters installedthatknowhowtoprintPDFfiles.AllmainstreamLinuxdistributionscome withGhostscript.ThisisafreeimplementationofAdobe'sPostscriptfilters.These

103

filtersareusedtomakesurethat"Whatyouseeiswhatyouget",touseahackneyed expression. Howtoprint Ifyouwanttoprint,youshouldpushthe"print"optioninthemenu.OK,youknow thatalready.Buthowdowegetfromthepointwhereyou'vegotLinuxinstalledto whereyoucanprintsomethingwithyourwordprocessor?Herearethesteps. 1.Installaprinter MostLinuxdistributionscomewithtoolsthatwillgetyouprintinginnotime.AsI mentionedbeforethatLinux'sprintingsystemisbasedonbasiclineprinting,you'll needaworking"printcap"file(tobefoundin/etc/printcap,usually)thattellsyour systemwhatprinterit'ssupposedtoworkwith.WithSuSEyoucanuseYASTto createthisfile(whichwillinvokeaprogramcalled'apsfilter'.RedHatcomeswith "printtool",Mandrakehasitsprintersetuptoolinitsmainconfigurationpackage. DebianandSlackwarebothusethe'apsfilter'toolaswell. Thislessonisnotmeantbyanymeanstobethedefinitivelistonproductsfromevery vendor,soifyourparticulardistributionisn'tlistedhere,you'llhavetoconsultthe documentationinyourcase. Forexample,the/etc/printcapfilethatSuSEconfiguredformymainmachineathome isthis: printer1ascii|lp1|y2prn_printer1.uppasciiprinter1|y2prn_printer1.uppascii:\ :lp=/dev/lp0:\ :sd=/var/spool/lpd/y2prn_printer1.uppasciiprinter1:\ :lf=/var/spool/lpd/y2prn_printer1.uppasciiprinter1/log:\ :af=/var/spool/lpd/y2prn_printer1.uppasciiprinter1/acct:\ :if=/var/lib/apsfilter/bin/y2prn_printer1.uppasciiprinter1:\ :la@:mx#0:\ :tr=:cl:sh: # printer1|lp2|y2prn_printer1.uppautoprinter1|y2prn_printer1.uppauto:\ :lp=/dev/lp0:\ :sd=/var/spool/lpd/y2prn_printer1.uppautoprinter1:\ :lf=/var/spool/lpd/y2prn_printer1.uppautoprinter1/log:\ :af=/var/spool/lpd/y2prn_printer1.uppautoprinter1/acct:\ :if=/var/lib/apsfilter/bin/y2prn_printer1.uppautoprinter1:\ :la@:mx#0:\ :tr=:cl:sh: # printer1raw|lp3|y2prn_printer1.upprawprinter1|y2prn_printer1.uppraw:\ :lp=/dev/lp0:\ :sd=/var/spool/lpd/y2prn_printer1.upprawprinter1:\ :lf=/var/spool/lpd/y2prn_printer1.upprawprinter1/log:\ :af=/var/spool/lpd/y2prn_printer1.upprawprinter1/acct:\ :if=/var/lib/apsfilter/bin/y2prn_printer1.upprawprinter1:\ :la@:mx#0:\ 104

:tr=:cl:sh: 2.InstalltheGhostscriptpackageandotherusefulfilters MostmajordistributionsalwaysrecommendtheGhostscriptpackagebydefault,soit goesonyoursystemwithanstandardinstall.Thiswilltakecareofyourmore advancedformattingneeds.Otherones,likethejpeglibrariesandotherimage formattinglibrariesarealsoinstalledbydefaultsoyoucanprintyourimagefiles easilyandpainlessly. 3.Turnontheprinterandpresstheprintbutton Isometimesforgettoturnontheprinter,sothat'swhyIincludedthislastpart. Someusefultroubleshootingtechniques Mostprintersworkfromaparallelport.Youmusthaveparallelportsupportenabled inyourkernel.MostmajorLinuxdistributionswillinstallagenerickernelwiththis enabled.Printingthereforeshouldn'tbeaproblem.However,mostpeopleatsome stageofthegameprefertocompileandinstalltheirowncustomLinuxkernel.When yougetuptospeedonLinuxandyoudecidedtodothis,alwaysremembertoinclude parallelportsupportintoyournewkernel.Ihaveforgottentodothis(whichironically seemstohappenwithmuchmorefrequencyasIgetfamiliarwithcompilingkernels) onlytofindthatIcan'tprintanythingwhenI'vefinishedinstallingmynewkernel. IhavealsonoticedmysystemchokeonstuffsenttoitfromCorelWordPerfect.I won'tgointothe"hows"and"whys"(becauseIhonestlydon'tknowwhyorhowthis happens)butIhavefellvictimtoaninabilitytoprintfromWordPerfectonoccasion. WhatIusuallydoisseeifinfactIhavepressedthebutton'print'andsomethingis waitingtobeprinted.Toseeifyouhavesomethingwaitingintheprinterqueue,just issuethecommand: lpq Thiswillshowyouwhat'sintheprinterqueueorifthereisinfactanythingthere. Outputgenerallylookssomethinglikethis,ifyouhaveaproblem(likemyprinter beingunplugged,inthiscase). waitingforprinter1tobecomeready(offline?) RankOwnerJobFilesTotalSize 1stbob46grocery_list.txt667bytes 2ndbob47lyrics_to_sinatra_my_way.txt2323bytes Forexample,ifIwantedtojustgetridofthesefiles,shutWordPerfectdownandstart itupagainandtryprintingagain(whichusuallyworksforme),Iwouldjustissuethe command: lprm Whichremovesthewholelineprinterqueue.Icouldalsobeselectiveaboutitand onlydeleteonofthefilesbytypingthecommand: lprm47 Alas,mydebutinthekaraokebarwillhavetowait,butIcanstilldotheshopping. Hopefullyyouwon'tneedtousethesetroubleshootingtechniquesveryoften,but they'regoodtoknowjustincase. EnjoyprintingunderLinux! UsingLinuxtoaccesstheInternet 105

Weliveinaninterconnectedworld.Infact,you'reusingthisinterconnectivityinform oftheInternettoaccessthiscourse.Chancesare,however,thatyou'reusingsome otherOStoconnecttoyourISPandreadthiscourse.Afterthislesson,youshouldbe abletoconnectandbrowsewhat'soutthereincyberspaceusingLinux. Onrampstothe"informationsuperhighway" Ithinkthattheterm"informationsuperhighway"isaperfectanalogyfortheInternet. That'sprobablywhyithasbecomesopopular.Thesuperhighwayitselfisthe telephonecompaniesinfrastructurethelines,fiberopticcables,switchesand satellitesthatbringthehundredsofmillionsofpagesofcontenttoyou,includingthis page.Yourcomputerislikethatcaronthehighway.Yourmodemorotherdevicethat connectsyouisliketheengineofyourcar.That'swhywe'vewrittenthislesson.If youcan'tgettheenginetowork,you'renotgoinganywhere.LinuxandotherOSesare abitlikethefuelyouputinyourcar.IfyouhavebeenusingWindows,that'slike usinggasoline.IfyouswitchtoLinux,that'sdifferent,likejetfuel.You'llhaveto modifyyourenginetobeabletouseit,butyou'llgofasterintheend. Typesofconnections TherearebasicallythreetypesofconnectionstotheInternet;leasedlines,broadband anddialupconnections. LeasedlinesarehighspeedconnectionsthatISPsusetoconnectyoutotherestofthe Internetorbigcompaniesusetocommunicatebetweenpartsoftheirorganizationand toallowyoutoconnecttothem.TheseareknownasT1andT3linesinNorth AmericaandEclasslinesinEurope.Thiscoursewillnotdealwithsettingupand Internetconnectionwiththeselines.It'salittleoutofthescopeofyouraverageLinux user. xDSL(DigitalSubscriberLine)andcablemodemarewhatisknownas"broadband" connections.Theseservicesoffer24hourhighspeedconnectionstotheInternetin mostcases(unlessyoushutoffyourmachine,ofcourse).Forexample,inmyarea,I haveADSLservice.Myconnectionrunsat250kilobitspersecondwhenIam receivingdata.Toputitinotherterms,Icandownloada5megabytefile(likeasong) inabout34minutes.Thisdependsalotonwhereyou'reconnectingtoandother factors,butbroadbandisthebestalternativeforhomeusers.Dependingonwhat companyisprovidingyouwiththisservice,youcanevenusethisconnectiontoserve yourownpersonalorsmallbusinesswebpageusingLinuxasawebserver.Inthe xDSLarea,youcanevenoptforhigherspeeds(upto2megabitspersecond)andhave Internetservicethatrivalsmuchmoreexpensiveleasedlinealternatives.Lately,cable modemisbecomingmorepopularthanxDSL,particularlyintheUnitedStates becausethecablecompaniesseemtohavegottenontheballfastertoofferconsumers highspeedconnections.Withallduerespecttotelephonecompanies,theremaybe, andIsuspecttherearelegitimatetechnicalreasonswhyacableconnectionis essentiallycheaperandeasiertoprovidetotoconsumers.Thereasonsbehindthis wouldgobeyondthescopeofthislesson,(andI'mnotatelecomengineer)sosuffice ittosaythatcableseemstobethewaypeoplearegoingtogethighspeedconnections totheInternet. Dialup(standardmodem)connectionsarebyfarthemostpopularwayofconnecting totheInternet.Upuntilthelate1990's,ifyouweren'taFortune500company,itwas 106

theonlywaytogetontheInternet.Thisconnectiontypebasicallyconsistsofusinga modemtodialthephoneandconnecttotheInternetServiceProvider(ISP).The modem"negotiates"theconnection(ietellstheISPwhoyouare)usingacoupleof establishednetworkprotocols.Thebestspeedyoucanhopetogetoutofadialup connectionis56kilobitspersecond.Thatistosay,about5timesslowerthanthe slowestbroadbandconnection. ISDNafootnote:Afewyearsago,inmyareaatleast,thetelephonecompanywas tryingtosellpeopleonISDN(IntegratedServicesDigitalNetwork)tosolvethetwo mainproblemswithInternetuse,namelytheslowmodemspeedandthefactthatyou couldn'tmakeorreceivephonecallswhileusingtheInternet.Theypromised connectionsofupto128kilobitspersecond(thekeywordsherebeingupto,using thetacticofcaradvertisementsthatsayfrom9,599dollars,butinreverse).Thishas neverseemedtohavecaughton,atleastinmyarea.ThefewpeoplewhoIknowwho hadthisservice(andlaterdroppedit)complainedaboutthespeed.Whatthey promised,justcouldn'tbedelivered.Atanyrate,nobodyseemstobetalkingaboutit somuchanymore. Let'smoveontothenextsectionwherewe'llshowyouhowtosetupthedifferent InternetconnectionalternativesunderLinux. ADSLwithLinux Fortunately(orunfortunately,dependingonyourrelationshipwithyourlocaltelecom company)thetelephonecompanyhandlesmostoftheheavyliftingduringtheprocess ofgettingLinuxtoworkwithanADSLconnection.Iwentthroughtheprocessof switchingfromstandarddialupnottoolongago,sotheprocessisfreshinmymind. HerearesomeofthethingsIhadtodo. 1. CalltheISP.Thisisprettyimportant.SometimestheywillofferyouInternet serviceandatthesametimearrangeforthetelephonecompanytocomeover andinstallasplitterwhichallowsyoutousethesamephonelinefordataand voicetransmission.Itisalsoimportantthatyouknowifyouaccepttheir services,youmayhavetoacceptthehardwaretheyrecommend(orforceon you).Therearetwomainconnectionoptions;viarouterandviamodem.They mayprettymuchobligateyoutouseoneortheother,evensellingyourtheir ownhardwareintheprocess.Inthebestcasescenario,askifyoucanuseyour ownchoiceofhardwareandthenhopetheysayyes. 2. ChoosearouterormodemIfamodemisn'tforceduponyou,thenit'sagood ideatochoosetherouteroption.Thebasicreasonforthisisthatitisusually platformindependentwhichmeansthatitdoesn'tmatterwhatOSyou'reusing becauseyoucanprobablyconfigureitusingTelnet(inmycase)orevenaweb browser,whichIhavealsoseendone.Forexample,inmycase,Ichosea routerthathadcapabilitiesforfilteringoutunwantedincomingconnections. Thisisveryimportantforsecuritybecauseyou'regoingtobeconnected24 hoursaday.Thisisagreatoptionforasmallbusinessbecausearouterallows youtopainlesslysharetheconnectionbetweenmultiplecomputers. 3. GetanEthernetcardIfyougotherouterroute(pardonthepun),you're goingtoneedanEthernetcard.Thesecardsaredesignedtoallowyouto connectcomputersinaLocalAreaNetwork(LAN).Mycardofchoice 107

(becauseitwastheonlyonetheysoldinmyarea)istheNE2000clones. Realtek8029PCIistheoneIuseinmymachinesinmyhomeoffice.Thisisa goodonebecausemostmajordistributionswilldetectthis(theyalwayshave forme)duringastandardinstallofLinux.Plus,evenifyou'veneverlooked underthehoodofyourPCyoucanmusterupyourcourageandinstallthis cardyourself.Forthefainthearted,Ihaveevenheardofthetelecompeople doingthisforyou.Youcanalsocallyourlocalguru.Iencouragepeopletodo itforthemselves.It'saquestionofusingasmallscrewdriver.Whatthat'sin, youconnecttheroutertotheEthernetcardsoyourPCcanreceivethedata.If you'vegotmorethanonePCinthehouse,youshouldgetanEthernethubto distributetheconnectionbetweenPCs. Puttinginalltogether Apicturespeaksathousandwords,soImadealittledrawingofmyhomenetworkto demonstratewhatapossiblesetupmightlooklike.(graphicscourtesyofTheGIMP It'sreallytoogoodofaprogramformypoorartisticskills!)

Twocables(red)comefromthesplitter.Oneisforthephoneandonegoestomy router.OneEthernetcable(green)goesfromtheroutertothehub.OtherEthernet cables(blue)gofromthehubtothePCs. Now,togetonthehighway Myhomenetworkisaprivatelocalareanetwork,soeachPCisassignedanIP addresswhichisanumberthatcomputersidentifythemselveswith.Incaseyoudidn't know,whenyougotowww.linux.org,you'reactuallygoingtoacomputerthatis assignedanumberontheInternet.Inmyhome,thesenumbersstartwith192.168.and thenhavetwonumbersafterthese.Thenumbers192.168.X.Xarereservedforprivate networks,soyouwillhavetousethese.Ifyouusedanyothernumbers,theymight conflictwithnumbersthatareactuallyoutthereontheInternet.IassignedmyPCsthe numbers192.168.0.1,192.168.0.2,192.168.0.3,192.168.0.4respectively. 108

Now,whenthetelecompeoplecametohookmeup,Itookoutmyrouterand connectedittothedatalinecomingfromthesplitter(seethepicture).ThenIhooked uptheroutertothehubandthenoneofmyPCstothehub.Inmycase,the manufactureroftherouterinthefactoryassignedthenumber192.168.1.1tothe router,soassoonasIturnediton,youcouldsayforallintentsandpurposesthatI hadanothercomputeronmylocalnetworkwiththeaddressof192.168.1.1.The routerwasequippedwiththepossibilityofusingaaprogramonaCDtoconfigure theInternetconnectionifIwasusingMicrosoftWindowsorTelnetforanotherOS, likeLinux. BeforeIusedTelnettoaccessthisrouter,Ihadtoknowwhataddressmytelecom companyhadassignedtomeforInternetpurposes.Thatistosay,whenyouusethe Internet,youdon'tidentifyyourselftoothercomputerswith192.168.X.X.With ADSLyouareassignedauniquenumberwithwhichtoconnecttoothercomputers. Thisnumberhastobeunique.It'salotlikerunningamen'sbowlingteam.Ifthereare 20membersand7ofthemarenamedBobthen,ifsomeoneannouncesthat"e;Bobhas thehighestscore"thenthere'sgoingtobeconfusion.Inmycase,Iwasgivenaunique number,let'ssayitwas20.20.20.20.ThenIusedTelnettoaccesstherouter.Iopened anterminalinmyPCandtyped: telnet then: open192.168.1.1 whichwasthelocalnumberedaddresstheroutercamewithbydefault.Theyalso furnishedmewithadefaultpasswordwhichIusedtoconnecttotherouter. Oncein,Ihadatextmodemenu(thebestyoucandowithTelnet)andgoingbythe router'smanualplusmylocaltelecom'sinstructions,Iassignedtheroutertheunique InternetnumberedaddressmytelecomhadgivenmeandthenIchangedtheaddress oftheactualrouterto192.168.0.5,tomemoreinsynchwithmylocalnetwork's numberingschemeandthenIchangedthepasswordtoaccesstherouter.Isavedthe changesandexited.Now,atleast,IhadADSLservicecomingintotherouter. ThefinalstepwastotellthePCswheretogettheirInternetconnectionfrom.Iwas usingmyworkstationtoconfiguretherouter,soIlogicallystartedwiththatone.Irun SuSELinuxonthismachine,soIhadtochange2files:/etc/route.confand/ etc/resolv.conf.ThechangesIhadtomaketookallof30seconds. First,in/etc/route.conf,Ihadtowritetheline: default192.168.0.50.0.0.0eth0 Whichmeansthat192.168.0.5isthedefault"gateway"totheInternet,orwherethe machineisgoingtorouteoutoftogettotheoutside.0.0.0.0isthesubnetmask(not importantforourdiscussionhere)andeth0standsforyourEthernetcardthatyou installedandisconnectedtothehubwhichisconnectedtotherouter. ThenIaddedtwolinestomy/etc/resolv.conffile. nameserver30.30.30.30 nameserver40.40.40.40 ThesearenottheactualnumbersIwasgiven.It'sjustanexampleIusedtocorrespond tothenumbersthatcouldbegiventoyoubyyourtelecomcompany.Thesearethe primaryandsecondaryDNSnumbers.DNSstandsforDomainNameServer.A 109

domainnameserverisjustamachinethathasaninventoryofothercomputersonthe Internet.Thatistosay,thesecomputersknowthatwww.linux.orgisactuallyanumber outthereandtheyhelpyoufindit.Withoutthesenumbers,youwouldn'tstanda snowball'schanceinhelloffindinganythingontheInternet.Ilearnedthisfactinmy hastetogettherestofthenetworksetup.WhenIwasconfiguringthelastcomputer,I forgottochange/etc/resolv.conffile.WhenIfiredupmybrowser,itbasicallydid nothinguntilIrememberedtochangethatfile. Ifyou'reusingMandrakeorRedHat,insteadof/etc/route.confyou'llhavetoaddtwo linesto/etc/sysconfig/network.ThesearethelinesIadded: GATEWAY=192.168.0.5 GATEWAYDEV=eth0 Thechangesto/etc/resolv.confarethesame. You'reonlinelet'sbecarefuloutthere Afterdoingallthis,Iwasonlinewithallmachinesgoingoutthroughtherouter.I quicklydisconnectedthehubtoallbutonemachineandfollowingtheinstructions, andsetupsomenecessarysecurity.Thisisimportantbecauseyouareasittingduck forintruderswithADSL.Youmaynotthinkthatyourlocalhomenetworkmightbe importantcomparedtosomecorporatewebsite(which,itreallyisn'tasfarasatarget forhardcorehackers/crackers)buttherearealotofmischievouspeoplewithtimeon theirhandsthatgoaroundlookingfortrouble.Thesepeopleusetoolstheygetoffthe Internettoscannumbersatrandomtoseeifthemachineattachedtothenumbercan be"hacked".Mostofthesepeople,popularlyknownas"ScriptKiddies"seldomknow howthesoftwareworksandreallydon'tcare.Theyjustknowtheycandoharmwith it.Astheysay,alittleknowledgeisadangerousthing.IRCchatisagoodplaceto chatwithfriendsandalsoagoodplacetoinadvertentlyinvitepeopletotakeaswipe atyourmachine.MostpeopleonIRCaretheretosocialize,seektechnicalhelpand evenworkandcollaborateonprojectsatadistance.Butthereareafewpeoplewith dubioussocialskillswhoarejustonIRCtobejerks.Alotofthesepeoplearescript kiddieswholiketogetinfeudswithpeopleonchannels.SeeingasIRCcantellalot aboutwhereyouare,youaresomewhatvulnerabletothesesociallyunacceptable charactersandwhattheymaytrytodowithyou.Remember,theydon'thavetoknow howtheprogramworks,onlywhatitdoes.Reportanythreatstothechannel operators.Sometimestheperson'sISPfiguresintheinformationonIRC.Reportthem totheirISPorthelocalauthoritiesiftheythreatentodoharmtoyourmachine. SecuritywithADSL SecurityinLinuxiswayoutofthescopeofthisbeginners'courseonLinux.Thereare acoupleofthingsthatyoucandowithouthavingtobeaguruonsecuritytohelp secureyourLinuxbox. Abriefexplanationofports Iwasluckyinthatmyrouterhastheabilitytofilterpacketsbuiltintoit.Packetsare thedatathatcomesinandoutofyourcomputerwhenyou'reconnectedtoanetwork, liketheInternet.Thepeoplewhodesignedthebignetworkofnetworkscameupwith theconceptofportsorpointofentrytocomputersfromtheoutside.Forexample, webserversrunonport80.Ifauseronanetworkwantstoaccessawebpageona server,theircomputermakesarequesttoport80ontheservertosendthemthepage. 110

That'saprettysafeport.Ithastobe.TheWWWwouldn'tfunctionifitdidn't. Actually,itisn'ttheportitselfthatshouldbeconsideredsafeorunsafe,it'sthe softwarerunningthebehindit.Apache'swebserverisprettysafe.But,aswehave seenwiththefamousCodeRedworm,Microsoft'swebserverIISisn't.Telnet,for examplerunsonport23.That'saportthatItoldtherouternottoacceptconnections to.Telnetisa'shell'awaytoconnecttoaremotecomputer.Thepasswordsyousend toconnectviaTelnet,eventhoughyoumayseelittleasterisks(ornothing)canbe pickedupeasilybypeoplewho'sniff'thesepasswords.Ialsodisabledmycomputer's abilitytoacceptconnectionviaTelnet.IsubstituteditwithSSHorSecureShell. SuSELinux'smostrecentoffering,(v.7.2atthetimeofthiswriting)enablesSSHby default.SSHacceptsremoteconnectionsthatareencryptedorcoded.Thatmakesit almostimpossibleforsomeonewhoyoudon'twanttotoconnectandtrytodoharm toyourcomputerfromtheoutside.SSHrunsonport22.IalsohaveFTPdisabled (port21). Firewalls Afirewallisjustabarrierbetweenanetworkthat'sinsideahomeorcompanyandthe outsideworld.Ifyourprivatenetworkdidn'thaveafirewall,peoplecouldjustconnect toitandseewhattheywanted.Itwouldbelikeahousemadeofglass.Peoplewould spendthedaythrowingstonesatit. Anydecentnetworkthat'sconnectedtotheInternethasafirewall.Thesubjectof firewallsgoeswaybeyondthescopeofthisbeginner'scourseandIdon'tpretendto explainhowtosetupafirewallhere.Somebigcorporationspaypeoplebigmoneyto setupfirewallsintheirorganizationsandthentheygethackedanyway.Ialwaysthink ofGoldfinger'scommentintheJamesBondmovieofthesamenamewhenhe explainshisplantostealthegoldfromFortKnoxtoabunchofincredulousMafiosos. 007'sredheadednemesissays:"Itisabanklikeanyotherandbankscanbe,howdo yousay'knockedoff'"IfyouwantagoodguidetoprovidingsecurityforyourPC runningLinux,IsuggestyoureadBobToxen'sRealWorldLinuxSecurity:Intrusion Prevention,DetectionandRecovery,thebestsellingbookonsecurityfromaLinux perspective. Practicalprotectionforthebeginner AgoodwaytoprotectyourLinuxmachine,whenyoudon'tknowtoomuch(yet) aboutsecurityisbymakingthefollowingverysimplechangesintwofiles:/ etc/hosts.denyand/etc/hosts.allow First,in/etc/hosts.denyaddthefollowingline: ALL:ALL Thisismeanttoblock(1stALL)servicesthatyourcomputerprovidesfromanybody (2ndALL)thatmaytrytologintoyourmachine.Then,ifyouhavemorethanone computer(asmallbusinessorhomenetwork)youshouldaddthislinein/ etc/hosts.allow ALL:192.168.0. Thiswillallowlocaluserstoaccessthecomputer.There'snoreasonnottoletpeople locallytologinviatheSSHprogramthatwementionedbefore.ThisisOKaslongas youtrustthem.Ifyouareahomeuseryou'reprobablysafebutifyouareusingthisto setupasmallbusinessnetwork,Iwouldbeabitmorecareful.Thereareallkindsof 111

storiesaboutdisgruntledemployeestakingliberties,revenge,extendedvacationswith companymoney,etc. Onelastword:ThisISN'Tasubstituteforafirewalloraserioussecuritysetup.If youaresettingthisuponasmallbusinessnetwork,pleasereadsomebooksorseeka professionalsecurityconsultant'shelp. DialupconnectionswithLinux DespitetheincreasingpopularityofbroadbandInternetaccessandcablecompany's venturesintotheInternetbusinessandtheirofferingofconnections,thevastmajority ofpeopleintheworld,atthetimeofthiswriting,connecttotheInternetviatelephone dialupthroughtheuseofastandardmodem,usuallyatspeedsrangingfrom14.4to 56kilobitspersecond(kbps).Thepurposeofthislesson,therefore,istodiscussthe waytogetadialupconnectionrunningunderLinux. Therearemodemsandthenthereare"winmodems" Onceuponatime,thereweremodems(whichstillexist)wheretheabilitytouseitto connecttocomputernetworks,liketheInternet,wasbasedontheconfigurationofthe hardware.Nevertheless,companieslikeMotorola,Rockwellandothersdeveloped modemswheretheconfigurationofthedevicewasmadepossiblethroughsoftware morethantheembeddedprogrammingonthehardware.Thissoftwarewas exclusivelycompatiblewith,yes,youguessedit,MicrosoftWindows.Theybecame knownas"winmodems".Untilrecentlyitwasimpossibletogetoneoftheselittle jewelsintheMScrownrunningunderLinux.Ifyouhappentohaveone,youcould checkoutLinmodems.orgformoreinformationaboutinstallingdriversfortheseto rununderLinux.Motorolarecentlyreleasedasetofdriversfortheir"winmodems". Thebestandeasiestway,however,ofmaintainingadialupconnectionisusingan externalmodemoraninternalmodemwherethehardwareprimarilyisdesignedto handletheconnection.BeforeIhadanADSLconnection,IusedanexternalDynalink 56kbpsmodem.ThesetupofthismodemunderSuSELinux,RedHat,Mandrake andSlackwarewastrivial.BeforethatIuseda38.8kbpsinternalmodemanda28.8 kbpsonebeforethat,upgradingasthehigherspeedsbecameavailableandtheir decreasingpriceswarrantedthechange. ExternalModems Externalmodemsarecalledthatpreciselybecauseyouhavealittleboxthatsits outsideyourcomputer.Theseconnecteitherviaaparallelportoraserialport.A parallelportisonethatisnormallyusedtoconnectaprinter.Aserialportissimilarin appearancetotheonethatisusedtoconnectyourmouse.Forexample,onmy workstation,whereIamwritingthislesson,therearetwoserialports,knownas "com1"and"com2".Asyoucanrememberfromourlessonsonothersubjectssuchas harddrivesandfloppydrives,Linuxalwaysknowsthesedevicesbyothernames,files thatresidewithinthe/dev/directory.Inourcase,Linuxknowscom1andcom2as/ dev/ttyS0and/dev/ttyS1respectively(inthecomputerworld,weusuallystartcounting atzero).Ifyouhaveaserialmouse,thisisusuallyoccupyingcom1andtherefore/ dev/ttyS0.Ifyouthengetanexternalmodemandyouwanttouseit,youwouldhook ituptothesecondserialport,com2,which,asImentioned,Linuxknowsas/ dev/ttyS1.Thetrick(reallynotatrickbecausethereisnodifficultyinvolved)isto

112

alteryourLinuxconfigurationsothatitknowsthatyou'vegotanexternalmodemon/ dev/ttyS1soitcancommunicatewithit. UnderSuSELinuxforexample,thisisquiteeasy.As'root'youwouldfireuptheir configurationtoolcalledYASTandchoosetheoption'SystemAdministration'and thentheoption'IntegrateHardwareintoSystem'.Atthispointyou'reaskedtochoose thehardwareyouwanttoconfigureandobviouslyyouwouldchoose'Modem configuration'whichisthesecondoption.You'llseethevarious"com"portsavailable andeven,withthenewerversionofSuSE,USBmodemsupport.Ifyouhaveaserial mouse,besuretochoosecom2or/dev/ttyS1.Youshouldhaveyourmodemsetup afteryou'vedonethis. Ifyou'veinstalledRedHatLinux,thenyoushouldhavenoproblemsettingitupwith oneoftheirutilitiesknownasmodemtool.Ifyou'veinstalledMandrake,theirtool HardDrakeshoulddothetrick.LinuxConfisalsoanallpurposetoolthatincludes modemconfiguration.Ihavehad(andheardof)mixedresultswiththistool. Nowthatyou'vegotamodemconnected,we'lltalkaboutconfiguringyourconnection withyourISPinthenextpartofthelesson. GettingintouchwithyourISP Therearealotoftoolsouttheretoassistyouinestablishingaconnectionwithyour ISPsoyoucangetoutthereontheInternet.Mostwilldothejobquitenicely.Ihave foundoneinparticularthatistheeasiestofalltouse.Notsurprisinglythatitiscalled eznet.ItwaswrittenbyRichardHippanditmakessettingupyourInternetconnection absolutelytrivial.ForRedHatandRPMbaseddistributionsthereisaRPMpackage compiledbyKentRobottiandavailablethroughRPMfind.net.Thereisalsoa "tarball"availableatIbiblio'swebsiteIfyou'refeelingadventurous,youmightwantto gotoDr.Hipp'swebsiteanddownloadtheCsourcecodeandcompileit,whichis anotheroption. Basically,theprogramasksyouaseriesofquestionsaboutyourISP,information whichthiscompanyshouldhavegivenyouandaboutwhereyourmodemislocated, (whatwecoveredintheprevioussection).Thereisapossibilitytohandleseveral differentISPs(atonepoint,Ihad3differentISPsconfigured).Onceyou'veanswered thequestionsandyouhaveyourconnectionsetup,connectionisnothingmorethan typingonecommandinaterminal: eznetup0 TheprogramstartscountingISPswiththenumber0,sothat'syourfirstISP.Just substitutefor1,2etc.forotherconnectionsyoumaywanttosetup. Otheroptions IfyouuseYASTinSuSELinuxyoucansetupyourconnectionusingWvDial.Imust confessthatearlierversionsofthisprogramwerenotentirelysuccessfulinsettingup myconnection.Euphemisticallyspeaking,theycouldn'tdoit.Thisprogramhasbeen greatlyimprovedandyourprobabilityofsuccessalongwithit. Ifyou'vepickedoutyourwindowsmanageralreadyandithappenstobeKDE,you're inluckbecausethereisaprogramcalledKPPPwhichwillsetupaconnectionfor youfairlypainlessly.TheonlyproblemIseemedtohavewiththiswasisknownas the"negotiation"oftheconnectionwithmyISP.Therearetwoprotocolsknownas PAPandCHAP.Ifyourunintothisproblem,itjustmightbeaquestionoftryingone 113

ortheotherandstickingwiththeonethatworks.WithKPPP,youcanalsotuneor tweakyourconnectionspeedtogetbetterresultsfromyourhardware. UserofRedHathaveaverypowerfulandsimpletousegraphictoolwithRP3.This isstandardissueonallversionsofRedHatsince6.2 Forthetechnicallycurious Asyou'llnotice,theprogramImentionedforKDEiscalledKPPP.TheKstandsfor KDEbutwhatdoesthePPPstandfor?ItstandsforPointtoPointProtocol.This protocolenablestwocomputerstoconnectacrossanetwork.Theprotocolbasically providesthemeansforthetwocomputerstofirst,identifythemselvesandthenask whetherwhetherthecomputerscanreadthedataeachothersends.Inyour/sbin/ directory,you'llfindthepointtopointprotocoldaemon,orpppdwhichisaprogram thatprovidesforthatcommunicationbetweencomputers. WhatyouessentiallydowhenyousetupyourInternetconnectionistomakesurethat pppdknowshowtocommunicatetherightinformation.Ifthetwocomputerseither can'tauthenticatethemselvestoeachother(ierealizethattheyhave"permission"to communicate)orthetypeofdatatheirsendingisincompatibleorboth,thenthe connectionfails.Whateznet,kppp,RP3andothersimilarprogramsdoaretocreate thenecessaryconfigurationfilesthatpppdreads.WhenIfirstsetupanInternet connectionwithLinux,Icreatedthesefilesbyhandwithoutthehelpofoneofthese programs.Itwasaninterestingexercisebutessentiallytookalongtimetofigureout atthosedays.Ifyou'reinterestedinfindingoutwhatgoesonbehindthescenes,I suggestyoucheckoutthepageLinuxDialUpNetworkinginaNutshellwhichhasa nicelistoftheprocessesandfilesthatcomeintoplay. Acommonproblem ThemostcommonproblemIhavecomeupagainstisthatsomehowthevery importantconfigurationfile/etc/resolv.confgetsoverwritten.Thishappenswithsome LinuxdistributionsandthereasonsarenumerousandIusuallychalkituptowhatI calledexcessive"meddling"withimportantconfigurationfilesonthepartofsome majorLinuxdistributions.Thesymptomoftheproblemusuallyisthateventhough you'veconnectedtoyourISP,you'renotreachingpagesoutthere.Thefirstthingyou shoulddoismakesure/etc/resolve.confincludesthetwoormoreIPaddressesofthe domainnameservers;thosemachinesthattranslateforexample,www.linux.org, intoouractualnumericaladdress.AsImentionedinthesectiononADSL,itshould looksomethinglikethis: nameserver30.30.30.30 nameserver40.40.40.40 Yournumberswillofcoursebedifferent,butifyoudon'tseeatleasttwolineslike this:nameserverplusanIPaddress,thenyou'llhavetoadditagain.Thenyoushould findoutwhyandhowyourdistributionisoverwritingthisfilesoitdoesn'thappen again,unless,ofcourse,youwantitto.SuSE,forexample,hasasectionintheir YASTtoolwhereyoucanconfigureitnottooverwritecertainfileslikeresolv.conf. Thatprettymuchsumsupsettingupdialupconnections.HappysurfingwithLinux! LessonEighteen GettingLinuxtomakesounds Thehillsarealive.... 114

Ifyou'relikeme,thefirstthingthatinterestsyouinsettingupyourcomputeris makingitplaysounds,particularlymusic.WhenIinstalledSlackwaresomanyyears ago(1997seemslikeaneternityforLinux)IthinkIwasmoreinterestedinmaking mysoundcardworkthanmakingthemodemworktogetconnected.Musichas alwaysbeenprettyimportantinmylifelongbeforetheWorldWideWebeven existed,sothatwasprettylogical. SoundCards WhenIboughtmyfirstsoundcardinDecemberof1992,itcameinabigboxthat CreativeLabssoldmeanditwasaSoundBlaster.Inthatbigboxtherewasabunch ofstuffsoftware(forWindows3.1),aCDROMdrive(withaninsertablecartridge thatmy2yearoldjustmanagedtobreakafteralltheseyears!)andsomeMidigadget whichneverinterestedmeandisstillinthesameboxinmyattic.Ihadgoodluck withthatsoundcard(Istilldobecauseitstillworks).Duetothis,Ihavealways boughtSoundBlastercards.Thesecardshaveusuallyconfiguredfairlyeasilyunder Linux.IwasonceboughtamachinethatdidnothaveaSoundBlasterbrandcardinit andIwasnotabletogetitconfiguredunderLinux.Ihonestlydon'trememberthe nameofthecardandIpromptlypaidalittlebitmoremoneyandexchangedthatone forarealSoundBlasterandquicklygotitrunningunderLinux. SoundBlasterusestheAlsadriverstomakesoundcomeoutofyourLinuxmachine. ThesepeoplehavemademylifemuchricherasIcanlistentolovelymusicasIwrite thislessonofthebeginner'scourse.Therearealotofothersupportedcards.My eternalgratitudetothepeopleworkingontheAlsaDriverproject.Youmightwantto havealookattheirlist.Andseeifyoursoundcardisontheirlist.Thenastyhardware manufacturerswhodo*not*sharetheirinformation(andtherefore,theircardsdo *not*work)arelistedinred. IfyouusetheSoundBlastercard,youmayalsowanttocheckoutCreativeLab'spage Configurationtools BeforeIgointothetoolstousetogetthesoundcardworking,it'simportanttopoint outthattheLinuxkernelneedstobeconfiguredtouseasoundcard.Ifyourkernel doesn'thaveaclueaboutwhattodowithaone,thereispreciouslittletoolslike sndconfigcandotohelpyou.Luckily,everyinstallIhavedoneinthepastyearanda halforsoofamajorLinuxdistributionhascomewithakernelthathassoundsupport initbydefault.Ifyou'reinstalling"Joe'sHomebrewLinux"distribution(whereyou mustcompileyourownkernel),thenyoumightbebeyondthisbeginner'sLinux courseandyouprobablyalreadyknowhowtomakethekernelyouwant.Butifyou areatruebeginner(that'swhothiscourseisfor)thenyou'reprobablygoingtogeta "madeforsound"kernel.ThelatestversionsofRedHat,SuSE,MandrakeandDebian thatIhaveinstalledareallsoundenabledfromthebeginning,dependingon,of course,whetherornotthehardwareismainstreamenoughtobedetectedoninstall.I wroteinareviewofMandrake7.2intheSpringofthisyear(2001)abouthowitdidn't detectmyverymainstreamSoundBlaster16card.ThegoodthingisthatMandrake 7.2isverymuchathingofthepast.They'reonversion8.1atthetimeofthiswriting andonthatsamemachine,Idida"clean"install(IdidnotupdateIremoved7.2and installed8.0new)anditfoundandconfiguredmySoundBlaster16cardwithoutthe

115

slightestproblem.Ifthedistributionyouhaveinstalled(orareplanningtoinstall)is uptodate,youshouldnothaveaproblem. Itisalsoimportanttoknowwhattypeofsoundcarditisintermsoftheslotsthatit usesonyourmotherboardinyourcomputer.Onmymachines,themotherboard(that bigthinginsideaPCthatyouplugallthecardsinto)ormainboardasitisalsoknown, willacceptISAPlugandPlaycards(biggerslots)andPCIcards(smallerslots).I'm notaUSBuser,soIwon'tfeignexpertisehereandgiveUSBguidelines.Ifyouhave anISAPnPcard(Ihavetwo)youalsohavetohavetheISAPnPtoolsinstalledas wellasakernelthatcanuseISAPlugandPlay(alsoknowasplugandpray) AsImentioned,mostmajordistributionswillconfigurethesoundcardduringthe installationprocess.Ifthisisnotthecase,youmayusetoanyofthefollowingtools, dependingonyourdistribution. sndconfigImentionedthisoneabove.ItisatoolforRedHatanddistributions basedonRedHat(Mandrake,KRUD,forexample).Itistextbased(runsita terminal)andhasalwaysdoneagoodjobforme.Itwillplayasoundbitof LinusTorvaldspronouncingtheword"Linux" YASTThisisSuSE's"SwissArmyKnife"ofconfigurationtools.Theirlatest version2isgraphical.Again,therewasnoproblemdetectingmysoundcards withYAST.Itplaysalittlemelodythat'salsotheKDEdefaultstartupsound. Youcanadjustthedefaultvolumeaswell.Itwarnsyounottosetittoohigh, justincaseyou'rewearingheadphonesandyoublowyoureardrumsout!! HardDrakeMandrakeusesthisgraphicaltooltoconfigurehardware, includingsoundcards.UsingtheGUI,youcanselectthesoundcardandthen pushthebuttonthatsays"launchconfigurationtool".Isuspectthatwhatitis doingislaunchingsndconfigwhich,asImentioned,isalsoavailablefor Mandrake. alsaconfIfyou'reusingDebian,thisisthepackageyouneedtosetupsound. Thealsabasepackageisalsorequired. Youshouldnowhaveaprettygoodideaofsettingupasoundcardwithamajor Linuxdistribution.Strangehardware,oldversionsofLinux(yourcousinlentyouthe SuSE5.3disks)andobscuredistributions(Zingblatter'sUltraLinux1.4)arebeyond thescopeofthiscourse,soifyou'reoneofthoseouttherewhopineforthesweets soundsofMozartflowingfromyourPC,youcantakealookattheHOWTO'sonthe subject.Youcanalsogotoyourfavoritesearchengine(mineisGoogle)andenter Linuxsoundcardsetupandyouhaveaccesstothezillionsofbytesofinformationon thetopic. Let'sgoonnowtoalloftheavailableprogramstoplayallofthatsoundandmusic, fromtheBeatlestoHansandhisSwissAlpineYodelers. Nowthatwehaveoursoundcardworking,it'stimetocheckoutsomeoftheoptions thatwehaveforplayingsound.Ifyou'refollowingthecourseinorderofthelessons, wehaven'tbeguntotalkindepthabouttheuseoftheXwindowsysteminLinux,so thetoolsforplayingandrecordingsoundherewillbeusedfromthecommandline. I'dalsoliketoaddaneditorialcomment,ifImay.Iuseawindowmanagerbutthe programsIlistentoCDs,MP3setc.arecommandlineapplications.Iamnotimplying thattherearen'tsomefineprogramsforplayingandrecordingsound.Therecertainly 116

issomenicestuffoutthere.TheprogramsIuse(whichwe'lltalkabouthere)aregreat applicationsthatworkjustaswellastheirgraphiccounterpartsbutinmanywaysare moreeasilyconfigurable,atleastforme.Besides,we'retalkingaboutsound,soIjust havetosettheCDorplaylistandlisten.Ireallydon'thavetoseeanything. RecordingSound DuetoMicrosoft'smonopolyonoperatingsystems(yes,theyhavebeenconvictedof thisinacourtoflaw),themostpopularformatforsoundrecordingisistheir*.wav format,alsoknownasPCM.Whenyoumakearecordingofyourselforsomeoneelse speakingoryou"rip"atrackfromaCDforlaterconversiontomp3orogg(we'lltalk aboutthisnewandopenformatlater),you'reprobablygoingtousethe*.wavformat. IfyousimplywanttorecordyourselfsayingsomethingusingLinux,allyouneedisa microphoneandandrecordingtoolthatgivesyouafileinthisformat.Forthislesson, we'lluse'wavrec'. 'wavrec'iseasytouse.It'seasybecausethedefaultrecordingsettingsforthis applicationsareallacceptableforgettingaqualityrecording(ifyou'vegotafairly goodmicrophone).Youjusthavetotypesomesimplecommandsandyou'reallset. Here'sanexample: Let'ssayIwanttorecordanotetomyselfthatsaysthefollowing:"Notetoself:make sureyourespondtoDave'semailaboutSuSE'.Iwouldjusttypethefollowing" wavrecdave_note.wav makesurethemicrophoneison(you'dbesurprisedhowmanytimesIforgettoturnit on!)andstarttalking.Thedefaultrecordingtimefor'wavrec'is10seconds.That means,ifyoudon'tspecifyarecordingtimeonthecommandline(Ididn't)you'llgeta 10secondlongsoundfile.Mysentenceabove,"Notetoself.....blablabla"lasts about8seconds.Ofcourse,thedurationofthesoundfiledependsonwhetheryou're talkinganormalrate.IfyouauctioncattleinIowa,thenyouprobablydon'tneed10 secondstosaythatsentence,soyoushouldmodifythetimeforthefile,likethis: wavrect3dave_note.wav Thetoptionreferstoseconds,soyoushouldtypethenumberofsecondsafter.Here, even3secondsmightbepushingitforacattleauctioneer.Justremembertogive yourselfenoughtimeforwhatyouwanttosay,inseconds.Ifyouwanttorecite AbrahamLincoln'sGettysburgAddress,thenyouwouldfirstmultiply60and2toget 120seconds.Whythisfigure?BecauseLincolnisreportedtohavetakenonly2 minutestogivethisfamousspeech.IfyouwouldliketorecordCubanleaderFidel Castro'sspeeches,thenIwouldadvisegettingahugeharddrive.Heoncemadea speechthatlasted7hours. Youcanaddallkindsofoptionstowavrec.Iusethistoolallthetimetorecordshort sentencesforuseincomputerassistedlanguagelearning.HerearethevaluesIuse: wavrecSt5s44100a_sentence.wav Let'sexplaintheseoptions.Thefirstone,S,meansstereo.Ifyoulookattheman pagefor'wavrec'(type:manwavrec),itsaysthatstereoisthedefault.Nevertheless,I havenoticedthatmonoisinfactthedefault.Thatistosay,ifyouuse'wavrec'withno options,yougetmononotstereosound.Itwouldseemthereisanerrorintheman page.AftertheS,wehavethetoptionforseconds(weexplainedbefore)thenwe havethesoptionwhichisthesamplingrateinHz.Ichose44100becausethisisa 117

goodhighqualitysoundwhichisnecessaryformylanguageteachingendeavors.It's importantnottoconfusetheS(capitalletter)withthes(lowercase).stakesavalue inHzwhileShasnovalue.Ihavepurposelyputthetoptioninbetweenthemto avoidconfusion.Thereyouhaveit.Issuingthisshortcommandandthenchangingthe filename,Igetalotofworkdonebecausemysentencesseldomlastmorethan5 secondsandthesevaluesarefineformywork. Now,youmustbeaskingthequestion:"I'vemadea*.wavfile,now,howdoIhear it?"Theansweriseasy:With'wavrec''scompanionprogram,'wavplay'.Here'show: wavplaya_sentence.wav Thiswillplaythesentencewerecordedabove.That'sallthereistoit.Ishouldalso pointoutthatthesameoptionsin'wavrec'areavailablefor'wavplay'ifyouwantto addsomeeffectstoplayback.Forexample,ifyoutakeourfirstwavfile, dave_notes.wav,andplayitlikethis: wavplays44100dave_notes.wav you'llfindit'sdoublyfast.That'sbecauseournoteaboutDavewasrecordedatthe default22050hz,soifyoudothemath,youseethatwhatwe'vedoneisdoubleit's samplerate.Youmightwanttodothis: wavplaymy_favorite_song.wav thensingalineofyourfavoritesong.Playitbacktoyourfriendsusingthes44100 optionandhavethemrollingonthefloorwithyourAlvinandtheChipmunks impressions.Ihaveactuallyentertainedmy2yearoldsonforhourswiththis. Usingthesamelogic,ifyoutakeoura_sentence.wavandplayitlikethis: wavplays22050a_sentence.wav you'vecutthesamplerateinhalfandsoyougetareallycoolimpressionofthe creaturesthattakeoverpeople'sbodiesinStarTrek'soriginalseriesepisode'The LightsofZetar'. Iknowwhatyou'reprobablythinking.Ineedtobeproductive.Idon'twanttorecord Chipmunksoundsandscifiweirdness.Well,then.Here'sagoodwaytousethese tools,plusacoupleofothercommandlinetoolstoreadreminderstoyourselfinthe morning,orwheneveryou'dlike.First,createasubdirectoryinyourowndirectory/ home/[you]/ mkdirreminders thengointoreminders(type:cdreminders).Now,Let'screateasortofintroductory wavfilethat'salwaysgoingtobethere.I'llexplainwhyweneedthatinabit. wavrect30intro.wav Saysomethinglike"Yourreminders"or"Remindersforyou".Threesecondsshould beenoughforthat.Youmayhavenoticedthatthenamebeginswithzero.Thatis simplebecauseforourremindersystem,weinvoke'wavplay*'withtheasteriskto playeveryfileinthatdirectory.Bynamingit'0intro.wav',thatassuresthatitwillbe playedfirstwithoursystem. Nowrecordsomereminders.IrecommendusingaYEARMONTHDAYformatplus somemeaningfulwordfornamingthewavfiles.Forexample,type: wavrect520011024_trash.wav andsay:"Remembertotakeoutthetrash".Isuppose5secondsshouldbeenoughto saythis.Tryrecordingafewmoreremindersfordifferentthings,like"callcousin 118

Jack"and"remembertopaybackgamblingdebtstobookie".Whenyou'vegotafew wavfilesinthereyoushouldplaythemtoseethatthey'vecomeoutallright(you don'tneedtodothiseverytimewe'rejustpracticing) wavplay* You'llseethatthe0intro.wavfilegetsplayedfirst.Ifeverythingsoundsgoodtoyou, thenwe'rereadyforthenextstepwhichistoplayourfilesautomaticallyatagiven hour. OneofmyfavoriteapplicationsinLinuxiscalled'cron'.Thisisaprettypowerfultool thatisusedprimarilybysystemadministratorstoautomatetheirtasksandduties.It's powerfulbecauseitcanschedulesomethingtoberunautomaticallyatanytime, whetherthatbeonceeverythreeminutes,everyhour,onceadayoreveryThursday.It canevenbeusedtorunajobthatyoudoonlyinJanuary.Butjustbecauseit's powerful,itdoesn'tmeanit'scomplicatedtouse.Forourpurposes,it'sverysimpleto configure'cron'toplayourreminders.First,wehavetoeditafilethatiscalled 'crontab'andaddourinstructions.Thereisasystemwidecrontabfileforroot's exclusiveuse,butthereisalsooneavailabletoeveryusertoruncommandlineapps thatheorsheisauthorizedtouse.Toaddajobtobedone,justtype: crontabe Thenweaddthefollowinglinetoourcrontabfile(eisforedit) 307***/usr/X11R6/bin/wavplay$HOME/reminders/*.wav Thecrontabeditprocedureusesyourdefaultcommandlineeditorwhichisprobably 'vi',soifyoudon'trememberourlittletourof'vi',justpress'ESC+i'beforeyouadd thisline. Let'sexplainhowacrontabfileworks.Thefileisreadbytheprogram'cron'andit carriesouttheinstructionsinit.Inourexample,ourwavfilesgetplayedatthe30th minuteofthe7thhour,thatistosay7:30inthemorning.Thisisbecausethecrontab filemuststartwiththeminute[059]youwantsomethingdone,followedbythehour [023]thedayofthemonth[131],themonthoftheyear[112]andthedayofthe week[07](where0and7arebothSunday).Ihaveleftthelastthreeasasterisk.This tells'cron'thatthesevaluesdon'tmatter.Thatistosay,cronshouldplayour*.wav fileseverydayofthemonth,everymonthoftheyear,7daysaweek. Thenextstepasyoucanseeistotellcrontorun'wavplay'andplaythefilesinyour homedirectory.Weusethesymbol$HOMEforthat.AlsonoticehowIhaveputthe exactpathtowherewavplayis.Toseeifyoursystemdiffers,thentype: whichwavplay toshowyouwheretheprogramis.Thenadjustaccordingly.Iusedthisexactpath because,itwouldseemonmysystem,themastercrontabfile(foundin/etc/crontab) doesn'trecognizethatpathautomatically.Iamassumingthatthisisforsecurity reasons,soIdidn'tgoinandchangethepath.Somethingsareprobablybestleft alone,sonoharmdoneifyoujustputintheexactpathinthecrontabfile. Ifyouwanttotestit,justgiveitatimewithinacoupleofminutesorso.Thatis,ifit's 3:30intheafternoon,youmightwanttofirstedityourcrontablikethis: 3215***/usr/X11R6/bin/wavplay$HOME/reminders/*.wav thatwillplaytheremindersat3:32PM,toshowyouthatitworks.Justmakesure you'renotplayinganythingelse,likeMP3s,becauseyouwon'thearthem.That'sthe 119

rationaleformy7:30AMstarttime.It'sagoodhourformewhenIamjustgetting toworkandI'mprobablynotlisteningtoheavymetalatthathourofthemorning. Actually,Ineverlistentoheavymetal. Now,whenyou'vefinishedhearingthem,youcandeletethem(ifyouwant)That's wheretherationalebehindtheYEARMONTHDAY.wavcomesin.Youjustdelete thedailyonesbytyping,forexamplerm20010928* Thatkeepsthe0intro.wavfileinthere.ImentionedbeforethatIwasgoingtoexplain whyit'snecessarytohaveitthere.'Cron'willmailyouwhenthereisanerror,soif youhadnoremindersforagivenday,youwouldatleasthaveonefileinthe/ remindersdirectory.Thatway,'cron'doesn'thavetomailyouanerrormessage becausetheprogram'wavplay'didn'tfindany*.wavfiles. Bydeletingtheunnecessaryreminders,you'vegotsomefreediskspace.Speakingof that,iffreediskspaceissomethingthatworriesyou,inthenextpartofthelesson we'lltalkaboutthosefamous(andcontroversial)filesthattakeuplessspaceMP3s andhowtomakethemunderLinux.We'llalsotalkaboutthenewfreeaudioformat comparableinsoundandspacetoMP3OggVorbis. MP3format Ifyou'vetouchedacomputerinthelastcoupleofyearsyou'veatleastheardaboutthe MPEGlayer3format,popularlyknownasMP3.Youhaveprobablylistenedtoan MP3andyoumayhaveeven"rippedatrack",thatis,madeanMP3filefromasong onaCD. MP3hasbecomesomewhatcontroversial.InlightoftheNapstercase,sharingMP3 fileshasopenedupaPandora'sBoxofquestionsaboutcopyright,fairuseand intellectualproperty.Thisreallyisn'ttheplacetodebatethosequestionsbutthereare someissuesrelatedtothemakingofMP3sthatconcernLinux,OpenSourceandFree Softwareinparticular. We'lltalkabouttheprogramsavailabletomakesoundfilesinMP3format,butI shouldpointoutthatMP3isanonfreeformat.Thatistosay,theFraunhoferInstitute andThomsonMultimediadevelopedMPEGLayer3technologyandtheyholdthe patentrightsit.Ifyouwanttowriteprogramsthatencodeand/ordecodeMP3format, youhavetopaylicensingfees.Thomsonhassetupawebsitetotalkaboutthese issues,ifyou'reinterested.WhatdoesthismeanforLinux?Well,ifyouarean advocateoftheOpenSourceand/orFreeSoftwaremodelthatLinuxgrewoutof,MP3 mightbeseenasaformattobeavoided.Actually,ifyouthinkthisway,younow haveanalternativewithVorbis'*.oggformat.We'lltalkaboutthatshortly.Butbeing thatMP3issoprevalentnowadaysandencoders/decodersdoexistforLinux,we'll talkaboutmakingandplayingMP3files. Let'sgobacktoour"reminder"system.Ifyougointothe/remindersdirectorywe created(cdreminders)andtype: lsl*.wav you'llseethatthedefaultqualityofa5secondrecordinggivesusafileofabout1/4 megabyte.Ifwemadethefilealittlebetter,asIdowhenI'mworkingwithsample sentenceforlanguagelearning,youdoubledthefilesizetojustunderhalfamegabyte each.Tocheckthis,Imadeoneofeachformat: rwrr1mikeusers132344Nov2712:110intro.wav 120

rwrr1mikeusers220544Nov2808:3720011128_fair.wav rwrr1mikeusers441044Nov2808:3420011128_good.wav Ifforsomereasonyouwantedtokeepthesereminders,filesofthissizewould quicklybegintotakeupspace.Diskspaceischeap,butthere'snoreasontooccupy spaceifwecancompressit.Wecouldtakeoutourtoolsgziporbzip2thatwelearned aboutinapreviouslesson.'bzip2'willactuallygetthefiledowntoabouthalfits originalsize: rwrr1mikeusers206442Nov2808:3420011128_good.wav.bz2 Butthereisamuchbetterwayofdoingthis,fornow,byconvertingittoMP3format. LookwhatwegetforthesamefileasanMP3: rwrr1mikeusers80234Nov2808:4820011128_good.mp3 You'vegotitdowntoaboutonefifthofitssize.Andyoucanhearitrightawaywith anMP3decoder/player.Let'sshowhowwedidthis. Firstofall,youneedaprogramthatconverts*.wavfilestoMP3format.Therearea fewoftheseavailableforLinux.Oneofthese,andprobablythemostpopular,isTord Jansson'sBladeEnc.He'shadsometroublewiththeMP3patentholdersso,again, we'vesteppedintocontroversyhere.Howdoweavoidbringingpatentholders'wrath downuponourselves?Well,bygoingovertoFraunhofer'swebsiteandgettingademo oftheirMP3encoder,appropriatelycalled'mp3enc'(thedemoisactuallycalled 'mp3encdemo'verylogical)wecanconvertthesefilesinMP3format.Thatwillat leastgiveusanideaabouthowallthisworksinLinux. You'llgeta*.tgz(Slackwarepackage)compressedfile.Justunzipanduntarinyour homedirectory: tarzxvpfmp3encdemo.tgz(orwhateverthecurrentfileiscalled) Thereisaprecompiledbinary(akaprogramthatworksrightaway)andsome documentation(manual,otherREADMEfiles).Thereisasectioninthemanualthat says"Fortheimpatient".Beingimpatientbynature,Iwentrighttothatandfoundout howtoconvertmy*.wavfilestoacceptablequalityMP3s.Now,we'reluckythatour remindersaren'tverylong,becausethegenerousFraunhoferpeoplehavegivenusa demothatonlyencodes30secondlongfiles.Iknowwhatyouwerethinking.You weregoingtorunnextdoorandborrowtheneighbor's"GreatestPunkLoveSongs" andstartrippin'.We'llyou'reoutofluckunlessyouwanttodoamedley.Atanyrate, theFraunhoferdemowilldonicelyforlearningpurposes.Tousetheprogram,just pickoneoftheremindersandtype: mp3encdemobr128000if2001[whatever].wavof2001[whatever].mp3 where[whatever]isthedateofyourreminder.Let'slookattheseoptions.brstands forbitrateThisis128kilobitspersecondandyou'llgetanacceptable,almostCD qualityfile.ifstandsfor"ifitworks"naahthat'sonlyajoke.(Icouldn'tresist).if meansinputfile,thatis,thefileyourinputingorfeedingtotheencoder.Logically then,ofmeansoutputfile,theMP3fileyou'regoingtoget.Thereyouhaveit.Feel freetoencodeanyfilesyouwant.(aslongastheirunderthirtyseconds,ofcourse) ActuallyanyMP3encoderforLinuxthatyoucanfindoutthereworksinbasicallythe sameway.Youinputa*.wavfilewithsomeoptionsandyougetanMP3file.The programBladeEncthatwementionedbefore,behavessimilarlyandthereisno30 secondlimit.(wink,wink,nudgenudge,andtheauthorbeginstowhistlenervously) 121

PlayingMP3files OK.NowwehaveourMP3file.Thatbegsthequestion:HowcanIhearit?Well,we needanMP3decoderand/orplayer.Isay"and/or"becausethesecouldbetwo differentthingsunderthexwindowsystem.PopulargraphicMP3playersareactually frontendsforMP3decoders.Thatmeanstheyprovideagraphiccontrolpanelfor usingaprogramthatyoudon'treallysee.That'swhyIusuallyusethecommandline programs,asImentionedearlier.Solet'ssavesomeCPUpowerandlearnhowthings workintheprocess. 'mpg123'isaverypopularcommandlineprogramforplayingMP3files.Itisalso highlyversatile.Youcancreateplaylistsandplaysongsinalphabeticalorderorin randomorder.Youcanevenplaylittletricksandcreateweirddiscoversionsofsongs. (nokidding)Youcaneven"reverseengineer"theMP3fileorevenpartsofitbackto *.wavformat.AsfarasIhavetried,mostgraphicprogramscanmanipulateplaylists andaddanechoeffectbutcan'ttakefulladvantageofmpg123'sfeatures.Youcan onlydoitonthecommandline. Anyway,'mpg123'comeswithmostmajordistributions.Ifyouvisitmpg123'shome pageyoucanfindoutallaboutit.YoucanalsogetsourcecodeandRPMsifyoudon't haveitinstalledalready. TosimplyplayanMP3file,enterthedirectorywherethefilesareandtype: mpg123your_mp3_file.mp3 Let'ssayyoualreadyhavealotofMP3s.Youmayhavegottensome...thenagain,I don'twanttoknowwhereyougotthem.Youcouldrandomplaythem mpg123z*.mp3 Oneofmyfavoritethingstodoistocreateaplaylist.Here'showIdoit.Thiswillbe goodreviewpracticeforthecommandlineaswell. First,IenteradirectorywhereIhaveMP3s: cdclassical ThenIseewhatsongsIhave: ls*.mp3 ThenIpickoutsomesongsthatIparticularlylikeandmakeafilethatisgoingtobe myplaylist: ls1Mozart_nightmusic.mp3>favorites Thecommand'ls'withtheoption'1'liststhefilenamewithoutanyotherinformation. The>symbolasyourememberfromourlessononpipes,etc.createsafilecalled 'favorites'andincludesthe'ls1'outputinit.Toaddmoresongs,wewouldrepeatthe samecommand,butthistimewewould(obviously)changetheMP3filenameand mostimportantlywewouldchangetheone>symboltotwo>>symbols.Thisway, wejustaddtotheplaylistfileandwedon'toverwritethefileaswouldbethecaseif wedidn'tusetwo>>symbols. ls1Beethoven_fur_elise.mp3>>favorites SoI'djustkeepaddingsongsuntilIhadaniceplaylist.Toseethelist,you'djusttype: lessfavorites Ifeverythingissatisfactory,thenwecanplaythesesongs.Justtype: mpg123@favorites

122

Theemail(@)symboltellsmpg123tolookfortheplaylist.Thatwouldplaythe songsintheordertheyareonthelist.Ifyouwanttoplaytheminrandomorder,you wouldjustaddazbeforethe@option Morefunwithmpg123 Let'ssayyouwantedtoplay"NameThatTune".Don'tlaugh!Ihavedonethisat parties.Youknow,youonlyplaysomuchofasongandthepeoplehavetoguess whichoneitis.Well,withmpg123,you'reallset.Thiscommandwillonlyplaythe first50"frames"ofasong: mpg123k0n50Mozart_nightmusic.mp3 Andyou'llhavetheliveliestpartiesonyourblock!AllcourtesyofLinuxand mpg123!Seriously,thekoptiontellstheprogramwhichframetostartatandthenn optionindicateswhereitshouldstop.Prettyeasy! Youwantmorepartyideas?Well,howaboutdoingTechnoMozart?That'seasytoo. Justtype: mpg123d2Mozart_nightmusic.mp3 Thiswillmaketheprogramskipoverevery2ndframe.Thatis,itwillplayaframe andskipone.Thisis*not*theChipmunkeffect.Youwillhearthesametoneofvoice becausethisdoesn'teffectthesamplingrateofthefile.Itwilljustsound"techno"asI pointedout.EventhoughImentionedpartiesandthat,Ihaveusedthisprogramand thiseffectinmylanguageworkforpurposesof"serious"study.Astherateofthe voiceisnotaltered,youcanchangethenumberandseeatwhatpointpeoplecan't understandsomething.Bythis,youcantesttheauralskillsofapersonlearninga language.Bytheway,youcanalsodotheoppositebychangingthedXoptiontoh X.Insteadofskippingframes,mpg123willplaythesameframeXnumberoftimes. Remember,theseoptionsdonotproducethe"slowmo"or"Chipmunk"effects.Itjust slowsdownthespeedofplayback. Aswementionedbefore,youcanalso"reverseengineer"theMP3filebacktoa *.wavformat.Remember,beforeyoutrythisathome,the*.wavformatisatleast5 timesbigger,somakesureyou'vegotplentyofharddiskspace. mpg123wMozart_nightmusic.wavMozart_nightmusic.mp3 Youcanalsousethedifferentoptionslikedorhcombinedwiththekandnto produceweird*.wavsoundeffectsfiles.Yourimaginationisthelimit.Ifyoudowant todotechnomultimediathingswithmpg123,youcanusethevoptiontoget completeinformationaboutthetrackyourplaying. Well,afterallthatissaidanddoneaboutMP3,ImustconfessthatIdon'tlike workingwithMP3sasmuchasIlikeworkingwiththenew,free(asinbeerand sourcecode)OggVorbisformat. Oggformat DuetotherestrictionsontheuseofMP3technology,OggVorbisisagoodwayto enjoydigitalmusicinacompressedformat.Thoughitisassociatedmorewiththe LinuxandOpenSourceworld,bothWindowsandMacintoshportsoftheOgg librariesarealsoavailable.Thisisproofofitsgrowingpopularityasadigitalmusic format.ThereareevencompaniesnowusingOggformatforsoundintheirgames. YoucanreadthelatestnewsonthestatusoftheOggVorbisprojectattheirwebsite. InstallationoftheOgglibraries 123

First,inordertolistentoandmakefilesinOggVorbisformat,youshouldtogoover totheOggVorbiswebsiteanddownloadsomepackagesthatareneeded:libao, liboggandlibvorbisThesearetheactuallibrariesthatdothecompressionand decompressionofthesound.Thecommandlinesoftwareforcodingandplayingthe *.oggfilescanbefoundinthereaswell,inapackagecalledVorbisTools.Included inthislastpackagearetheprogramsoggencandogg123.Thesearedesignedtowork inthesamewayasthepackagesbladeencandmpg123intheMP3world.Their commandlineoptionsareessentiallythesame. Beforeyouactuallyvisitthesiteandstartdownloading,ifyouhaveboughtaboxed setofamajorLinuxdistributionrecently,youshouldhavetheselibrariesincludedon theCDsandbeabletoinstallthispainlesslywithyourdistribution'sinstallationtools. IfyougotyourCDsfromyourcousinLarrywith"Redhat"writtenontheminmagic marker,thenfeelfreetogooveranddownloadtheRPMsatwww.vorbis.comand installthem,asyourememberfromourlessononRPMs. rpmilibao[whatever'scurrent].i386.rpm rpmilibogg[whatever'scurrent].i386.rpm rpmilibvorbis[whatever'scurrent].i386.rpm rpmivorbistools[whatever'scurrent].i386.rpm Note:Don'tgetthesourceRPMs(theonewith'src'inthetitle).Youwon'tneedthose ifyou'rerunningRedHatoranyRPMbaseddistribution(likeMandrake,KRUD etc.).Also,installintheorderIhavegivenyouaboveanddothisasthe'root'user Ifyou'vegotsomeotherdistributionlikeSlackwarethatworksbetterwithtarballs thanRPMs(orifyouarefeelingadventurous/masochistic,thengetthefilesending with*.tar.gz(thetarballs).Unzipanduntarthemandreadthereadmeand/orinstall fileswhichwillinstructyouhowtogetthosepackagesinstalledandworking.Itook thisfromlibogg'sownREADMEfile: ./configure make andoptionally(asroot): makeinstall Iguessyougettheidea.Nowlet'sseewhatwecandowiththeselibrariesand programstogetsomenicesounding*.oggfiles. MynostalgiaprojectwithOggVorbis TotryoutthecapabilitiesofOggVorbisandthecapabilitiesofLinuxingeneralfor manipulatingsoundIdecidedtoconvertto*.oggformatsomeoldanalogaudio recordingsthatIhadofa"garage"bandIwasinduringthelate70'sandearly80's. ThesewereproducedbeforethefirstCDseverappearedontheplanetusing8track reeltoreelequipmentinmybestfriend'sbasement.Variouscassettesweremadeof theoriginalrecordingsandIwantedtopreservethemdigitally.Italsogavemethe opportunitytooutlinetheproceduretouseasatutorialandtocowardlystayoutside therealmofcopyrightinfringementissues.Thereare,Iamsure,peopleusingLinux whogrewupinatimewhenthelettersCDonlymeant"certificateofdeposit"and wholistenedtovinylrecordsandaudiocassettetapes.Somemighthaveevenlistened to8tracktapesandareafraidtoadmitit.Ifyouhavestereoequipmentthathasa 124

turntableand/oraudiocassetteplayerwithlineoutplugs,thistutorialmayalsobe appliedtothepossibilityofmakingcopiesofrecordsandtapesforyourself,whichthe lawallows,ifyouownthem. Howtodigitallyenshrineyourpastdelusionsofgrandeur Needed: Oneunsuccessfulgaragebandofthe70's Acassetteofmusicofrockstarwannabes Audiocassetteplayerwithlineoutplugs Cablestoconnecttheplayertoyoursoundcard optionalMedicalinsurance(incaseyougetilllisteningtothemusic) Allsoundcardshaveinputsforyourspeakers/headphones,amicrophoneandalinein cable(thatis,thelineoutfromstereoequipment).Theirfunctioniseithercolorcoded (speakersareusuallygreen,microphoneredandlineinblue)orwrittenonthemetal bracketofthesoundcard.Plugthelineoutofthecassetteplayerintothelineininput onthesoundcard.Usually,themicrophoneisthedefaultsourceforrecording.You mayhavetofireuptheAlsamixerandchangethis.Type: alsamixer then,usingthearrowkeys,makeyourwayovertothelineincolumnandpushthe spacebar.Thatshouldactivateyourlineinastherecordingsource.Itshouldlooklike this:

Youcanalsoadjustthesoundwiththeuparrow. Somewhattarnishedbronzeoldies Now,IputmycassetteintheplayerandIwasreadytogo.Iplannedonusingthe wavrecprogramImentionedearlierinthislessontoconverttheanalogtapeaudioto *.wavfiles,butIdiscoveredaslightproblem.Ididn'tknowthelengthoftimethe songstooktoplay.Beingyourbasicallylazysystemadministratortype,Idecidedto tryalittletrick.Ifiguredthatnoneofthemcouldprobablylastlongerthan5minutes, soItypedthefollowing: wavrecSt300s44100stairway_to_the_basement.wav Thatmeantthatwavrecwouldcontinuetorecordfor300seconds(ie5minutes).You canchangethatforhowevermanysecondsthatyoulike.Isureyouremembertherest oftheoptionsfromearlierpartsofthelesson. 125

MyplanconsistedinpushingCRL+Cwhenthesongcametoanend.Atfirst,Iwas afraidthatwouldcorruptthedatabutwhenItriedit,itworked.Thefirsttrialrun soundedfineusingwavplay.SoIjustcontinueddoingthis: wavrecSt300s44100smoke_on_the_wafer.wav andpushingCRL+Cattheend.SoonIhadallmysongsconvertedto*.wavfiles. Thencamethetimetoconvertthemto*.oggformat. WorkingwithOggenc ThenIusedoggenctogetthemthisformat.Here'sanexamplewithonesong: oggencb192a"Grage_Band"l"DemoTapes"t "no_sympathy_for_the_neighbors"
no_sympathy_for_the_neighbors.wavn"%a_%t.ogg"

Let'sexplainsomeoftheoptions. bstandsforbitrate.Anythingabove128willgiveyougoodquality.Ichose 192herebecausethisisfairlygoodqualitywithoutbeingexcessivelybig. Aftertheaoptionyoushouldputtheartist(Iusethetermlooselyinmycase) inquotes. Theloptionisforthenameofthealbum.Wenevermadeanalbum,soIjust put"demotapes"asyoucansee. tstandsfortrackorthenameofthesong. Now,typethenameofthesongwhatever.wav nfollowedby"%a_%t.ogg"tellstheprogramtonametheOggfileforthe artist(%a)andthetrack(%t). You'venoticedthatIhaveputunderscores_between_wordsintrueUnixfilename fashion.That'sagoodidea.(DemoTapeexceptedthat'snotgoingintothefilename) ThatshouldcreatesomefilesinOggformatforyou.Onewordofcaution.BothMP3 andOggencodingisveryCPUintensive.Makesureyou'renotdoinganythingthat needsalotofCPUcyclesatthesametime.Ifyou'reinterestedinseeingjusthow CPUintensivethisis,justrunthecommand:topandthatwillgiveyouanidea. Onceagain,ifyou'vegotsomeoldtapesoroldrecordsandyouwanttomakecopies foryourself,here'sawaytodoit.Thereissoftwareavailabletotakethescratchy soundsfrom*.wavfilesmadefromLPs.Thereisgoodexplanationoftheprocessat uklinux.net. Well,enjoyallthoseoldcassettesandLPsandifyouwereonceaneighborhoodRock andRoller,thentryouttheOggVorbistoolsandtakeatripdownmemorylane. CompactDisks IlovethesceneintheAdamSandlermovieTheWeddingSingerwheretheYuppie junkbondtraderGlennGulia,bringsonofthefirstCDplayershometohisfiance Julia,playedbyDrewBarrymore.Guliaexclaims:"It'saCDplayeritcost800 bucks,butthesoundqualityisexcellent!"Irememberthosedaysin1980'swhenI heardmyfirstCDandwasamazednoscratchesnohiss.TheCD,aspromised, oustedtheLPrecordforever.NotsoonafterthereleaseofCDsandCDplayers, recordsdisappearedfromallbutcollector'sshops.Luckily,CDplayersdidn'tstay around800USdollarsforlong.

126

Soonsoftwarecompaniesrealizedthepotentialfordatastorageintheselittleplastic disksandtheCDROMmarketwasborn.Fromabout1992ontheuseofCDsin computersincreasedexponentially.Now,almost10yearslater,we'renotonlytalking aboutreadingCDsbutwritingtothemwithCDRWdrivesthatcostunder200US dollars.AspinoffoftheCD,theDVD(DigitalVideoDisk)isbecomingmoreand morepopulareveryday.Soonwewillhaveaffordabledrivesforhomeusethatwrite tothesedisksaswell. Linuxhasneverbeenbehindinsupportingthesetypesofmedia,sowe'llshowyou someoftheutilitiesoutthereforplayingandrippingtracksfromCDs. PlayingCDs AsIpointedoutearlierinthelessononsound,Iliketousecommandlineprogramsto playCDs.MyfavoriteoneandIthinktheonethat'seasiesttomanageistcdbyTim Gerla

Youcancontrolwhichtrackstoplay,adjustthevolume,ejecttheCDanddoother thingsallfromthekeyboard.Youcanuse'tcd'tokeepadatabaseofyourCDsfor easyplaying.UnderXwindow,youcanfireupthisbabyinanxtermandenjoy hoursoflisteningpleasure. GUIbasedCDplayersareplentifulaswell,andwhenyou'veinstalledandconfigured yourXwindowsystem,youcantryoutthoseaswell. RippingCDtracks ThewholeNapsterphenomenon,asIpointedoutatthebeginningofthisarticle,made thepracticeofconvertingsongsonCDs"rippingasitisalsocalled"verypopular. Herewe'regoingtotalkaboutoneofthemostwidelyusedprogramsintheLinux world.Theofficialpositionofthisauthoristhatrippingtracksfromone'sownCDs forpersonaluseisOKbyme(andthelaw,itwouldseem).Forexample,rippingyour favoritesongsandconvertingthemtoOggformattomakeitcomfortabletoplayyour favoritesongsfromyourdesktopdoesn'tentailyouventuringintolegalgrayzones.If yousharedthemhowever,that'sadifferentstory.So,ifyou'reinterestedinripping tracksfromCDs,theLinuxprogramparexcelencefordoingthatiscdparanoia. cdparanoiaisbilledasarippingtoolforCDdrivesthatcouldbeproblematic.It seemstoworkfairlywellonthevarietyofspeeddrivesthatIhavetriedexceptfora

127

coupleofancientones.It'savailablefordownloadfromthesamepeoplewhobring youOggVorbis.Here'showitworks: Let'ssayyouwantedtoriptrack(song)6fromaCD.YouwouldplacetheCDinthe drive(Ihaveforgottenthatonoccasionduh)andtype: cdparanoia"6" Theoutputwouldlooksomethinglikethis: cdparanoiaIIIrelease9.8(March23,2001) (C)2001MontyandXiphophorus Reportbugstoparanoia@xiph.org http://www.xiph.org/paranoia/ Rippingfromsector48423(track6[0:00.00]) tosector58677(track6[2:16.54]) outputtingtocdda.wav (==PROGRESS==[>|05008500]==:).==) Sonowyouhavetrack6,called'cdda.wav'(cddastandsforCompactDiskDigital Audio,bytheway)readytobeconvertedintoyourfavoritecompressedformat,like Ogg.Here'sarefresher.ToconvertyourrippedtracktoOgg,typethis:(changeitto yourinfo) oggencb192a"The_Rubber_Band"l"GummedUp"t"shes_elastic"cdda.wavn "%a_%t.ogg" NowyouhaveaniceOggfilethatyoucanplaywithogg123 Otheroptionsforrippingtrackswithcdparanoiainclude: cdparanoiaB ThiswillripthewholeCDintoseparatetracks,namedtrack01.cdda.wav,track02.cdda.wav, track03.cdda.wavetc. cdparanoiacdparanoiaB"5" Thiswillriptracksuptoandincludingtrack5intoseparate*.wavfiles.Ifyouwant onebigfile,justeliminatetheBoption.Donotforgettotypethedoublehyphens beforetracknumbers.Justtofinishoff,here'saninterestingcombination: cdparanoia"4[:45]4[2:15]" Theaboveexamplewillriptrack4startingat45secondsandendat2minutes15 secondsintothesametrack.Whywouldyouwanttodothis?Anumberofreasons youonlyliketheawesomeleadguitarpartofasong?Thatcouldbe.Anyway,the manualpage(type:mancdparanoia)isaparticularlywellexplainedone,soifyou wantmoreexamples,there'sagoodsourceofinformationthere. Well,thatconcludesourlessononsound.Youshouldbeabletolistento,createand manipulatesoundwithLinux. LessonNineteen GraphicUserInterfaceswithLinux 128

Somepreliminarycommentaryandperspective AsmuchasIlikeLinuxandthinkthatitisthebestoperatingsystemouttheretoday, mostpeoplewhousecomputersequateMicrosoftwithcomputing.Inparticular,the onlycomputingenvironmentthatmostPCusershaveeverseencomesinthe successiveversionsoftheirflagshipoperatingsystemWindows(tm).However, computerscientistsandpeoplewhohaveaninterestincomputersbeyondthemere enduserstageknowthatgraphicuserinterfacesordesktopenvironmentslike Windowsreallyrepresentthelookandfeelofthecomputerexperience,butnotthe experienceitself.Windowshasbecomefamousforessentiallyblurringtherealityof whatacomputerreallydoes.ThatistosaythatMicrosoftWindows,especiallysince thereleaseofWindows95,hasmaskedanytraceofthetraditional"black"computer screenexperience.Itwasstillthereyoujustcouldn'tseeitunlessyoupurposely lookedforit. BillGates,chairmanoftheMicrosoftCorporationoncestatedthat:"Linuxis1960's technologywithanewdevelopmentmodel".Whatdoeshemeanbythis?Ithink basicallythathebethiswholecompanyontheassumptionthatpeopledidn'twantto seethetraditionalblackscreenandthecommandpromptanymore.Thesalesof Windows95provedthatwithagoodmarketingcampaignhewasabletoselltheidea thatpeopledidn'twantitandpeopleresponded.ThenLinuxstartedtogainin popularityandbenoticedbyacertainsegmentofthepublicaround199899.The problemwasthatLinuxofferedtheblackscreenandthegraphicuserinterfaceasa separatepackage.BillGateshadalreadyestablishedthatthiswasanonoandso Linuxgetschalkedupas"retrograde". Nowit's2002andLinuxstillofferstheblackscreenandgraphicuserinterface separately.Butthenagain,alothashappenedsince1998.Forone,IBMhasspent1 billionUSdollarsonLinuxandessentiallygottenitsinvestmentback.Linux'smarket sharecontinuestorise.ItstillpalesincomparisonwithMicrosoft'sdesktoppopularity somuchsothatasmosteveryoneknows,Microsoftwasconvictedofbeinga monopolyinrestraintoftrade.Thenagain,in2000and2001successiveemailviruses andwormscrippledWindowsbasedITdepartmentsandbroughtscoresofcorporate networkstoagrindinghalt.Why?Becausewe'reinanewworldofconnectivity.Bill Gates'commentaboutLinuxmaybeturnedbacknowuponhisowncompany.Ifyou askedyouraverageLinuxenthusiastwhatheorshethinksofWindows,youmightget thisreply:"WindowsispreInternettechnologywithaslicknewmarketing campaign".Microsoftspendsmostofitsdaysnowfightingsecuritybrushfires becauseinblurringthedifferencebetweentheoperatingsystemandthegraphicuser interfaceitsacrificedsecurityforeaseofuse.Windowsdevelopmentmodelwas conceivedbeforeeverybody'scomputerswhereconnectedtoeachotherandit continuestoreflectthat.Linux,however,wasbornontheInternetandgrewupwith it.Unfortunately,morecomplaintsaboutLinux'sperceivedlackofuserfriendliness outnumbercomplaintsaboutWindowsbeingessentiallyaMaginotLinesolutionfor securecomputing.HopefullyinthislessonongraphicuserinterfacesunderLinux, you'llgetagoodideahowthebalancebetweenuserfriendlinessandsecurityisagood onewithourfavoriteOS. TheGUIfamilytree 129

Withoutgettingintoalotoftechnicaljargon,inorderforthosenicewindows(yes, withasmall'w')toappearonyourcomputerscreen,youhavetohavesomegraphics librariesinstalledonyourcomputer.Theselibrariesdeterminehowawindowisto appear,whatitissupposedtolooklikeandwhatthebuttonsandmenusaresupposed todo.ThatfactthatyoucanuseGUIbasedcomputingunderLinuxgoesbacktothe timebeforeLinuxwaseventhoughtof.InthemideightiesattheMassachusetts InstituteofTechnologytheycameupwiththeXwindowsystem.By2002standardsit wasaprimitiveGUIsystemtorunprogramswith.Themainideabehindthisactually camefromanearlierprojectatXeroxcalledWIMP(Windows,Icons,Menus, Pointer),aprojectthatessentiallystartedtheideathatcomputerscouldbeusedinan attractivegraphicalenvironment.1 The'XWindowsystem'providedthelibrariestomaketheframes,buttonsandmenus thatmakeupawindow.DevelopmentofXWindowstillcontinuesundertheauspices oftheXConsortium.In1992theXFree86Projectwasstarted.Thisaimedtodevelop afreeversionoftheXWindowSystem.TherehavebeenseveralversionsofXFree86 andthecurrentstableversionatthetimeofthiswritingisXFree864.0.Thoughthere areotherequivalentstothelibrariesthatXFree86offers,itisbyfarthemostwidely usedwindowsystemunderLinux.AnyattemptatusingLinuxasadesktopoperating systemtoget"productive"workdone(wordprocessing,spreadsheets)ortoentertain oneself(playgames,listentomusic,watchTV)willstartwiththeinstallationof XFree86. Withmajordistributions,theinstallprocesstakescareofgettingXFree86ontoyour system.Therearetwopartstothis.OneisinstallingXFree86itself.Theotheris installingtheXserverthatgoeswithyourparticularhardware.TheXserverisjustthe meansofgettingXFree86toworkwiththegraphicscardthatyouhaveinyour computer.Forexample,ifyouhaveagraphicscardfromATI,thenyouwouldinstall theXFreepackagesalongwiththeXserverpackageforATI.IfyouhaveanS3card, thenXFree86andtheXserverforS3cardsshouldgetinstalled.Iexplainthisbecause somedistributionsdoaprettyfinejobofgettingyouupandrunning,butyoumayget askedwhatgraphicscardyouhavewhenyoudoamoreinteractivetypeofinstallof Linux.Inthiscase,youhavetoknowwhatcardyouhavesothecorrectXservergets installedandyoucanhaveagraphicalenvironmenttolookataftertheinstallprocess isfinished. Recently,majorLinuxdistributionswillalsoofferyouthepossibilityofgettingright intotheGUIwhenyouturnonyourcomputer.Thisisdonebywayoftheprogram XDM.ThisistheMicrosoftWindowsinfluenceonhowthingsaredonethatI mentionedbefore.TraditionallyinLinux,youwouldturnonyourcomputerandget theblackscreenandthecommandprompt.Thenyouwouldtype: startx andyourgraphicalenvironmentofchoicecomesup.'Choice'isthekeywordhere.By havingthecommandpromptandthenissuingacommandtostarttheGUI,youcan switchintoanynumberofdesktopenvironments"onthefly".Ofcourse,ifyou'renot interestedinhavingmorethanone,thenyoucanuseXDMandhaveyourfavorite desktoptherewaitingforyou.

130

Regardlessofthewayyouchoosetostartupyourmachine,beforeyouseeyouryour desktoputilitiesofchoice,we'regoingtohaveconfigureXFree86touseyour monitor,mouseandkeyboard.Thatis,whetheryoutypestartxornot,we'llhaveto comeupwithacomeupwithaconfigurationsowecan,infactstartX.


1

TheXWindowUserHOWTObyRayBrigleb,1999

XWindowconfiguration InLinuxdaysofyore,itusedtobequiteatasktogetXWindowrunningevenona standardInteltypePC.Nowallofthemajordistributionshavetheirowntoolstoget Xrunninginnotime. SuSEoffersaprogramcalledSax.ThisisaboutthemostuserfriendlyprogramIhave yetencounteredforXsetup.Itisgraphical,sothesimplefactthatyoucanrunit beforeyou'veevenstartconfiguringXisagoodsign. MandrakeofferstheirXconfigurationrightintheinstallpackagesoyougofromstart tofinishallinthesamepackage. However,givenasituationwhereyourXsetupdoesn'tgosmoothly,youcandothis thisstepbystep,intextmode,withaprogramcalledxf86config.Thisisalastresort andwillalmostalwaysgetyougoodresults. Thisprogramasksyouquestionsaboutyourperipheralhardware,likeyourkeyboard, mouseandmonitor.Hereareacoupleofexamplesofwhatitlookslike:

Themostimportantquestionsthatthisprogramwillaskyouaboutyourhardwareare theonesaboutyourmonitor.Idon'tmeantoimplythattheothersarenotimportant. Forexample,ifyoudon'tanswerthetypeofquestionsaboutyourmousecorrectly, yourmousewon'twork.Orifyoudon'tenterthecountry/languagevaluesforyour 131

keyboardlayout,youmaynotbeabletouselettersorsymbolsthatexistinyour nativelanguage.Thatisobviouslyimportant.However,ifyoudon'tenterthevalues correctlyforthetypeofmonitoryouhave,yourmonitorcangetseriously damaged.Ifyouentertheverticalandhorizontalrefreshratesincorrectly,your monitorwillbecomejustanotheruselesspieceofplasticandglass,likesomany otherswaitingtobethrownawayorrecycled.It'sbeyondthescopeofthislessonto explainwhattheverticalandhorizontalrefreshratesmean(actually,it'sthehorizontal onethat'sarealstickler)buttrustmeyouneedtogogetthemanualsforyour monitorandentertherealvalueswhenitasksyou.Ifyoudon'tbelieveme,thisis whatxf86configsays
ItisVERYIMPORTANTthatyoudonotspecifyamonitortypewithahorizontalsyncrangethatis beyondthecapabilitiesofyourmonitor.Ifindoubt,chooseaconservativesetting.

Atthispointintheconfiguration,youcanchooseoption11andenteryourownvalues fromthemonitor'smanualsandyou'llbesuretogetthecorrectsettings. Onceyouhavepassedthispoint,thequestionsaremorestraightforwardanderrors havelessgraveconsequences. Inthepastyears,asImentioned,majorLinuxdistributionshavestreamlinedthis processsoyouprobablywon'tevenneedxf86config.Butit'snicetoknowyouhaveit there,especiallyifyourhardwareisprovingtobelessthancooperative. Tobootornottoboot(ingraphicsmode),thatisthequestion. Beforestarttalkingaboutthedifferentwindowsmanagersanddesktopenvironments thatareavailableforLinux,let'sfirstseehowourbarebonesXWindowsetupis working.SomeXprogramsdon'tneedawindowsmanagertorun,solet'stryasimple experimentwithoneofthem.Typethisinyourterminalwindow: xinit/usr/X11R6/bin/xedit Thiswillfireupasimpletexteditorcalled'xedit'.Youcantrywritingsomethingand pushingthebuttons.Whenyoupush'quit',you'llnoticeyougobacktoyourstandard terminal.Trythesamewithanxterminal: xinit/usr/X11R6/bin/xterm Typeinafewcommands.Thentype'exit'.Yourxtermsessionendsandyourbackin yourterminal. Thereisn'tanypracticalreasontouseXWindowinthisway.It'sbettertouseits powerfulcapabilitieswithafullfeaturedwindowsmanageranddesktopenvironment. Beforewegoontotalkaboutchoosingawindowsmanagerthatsuitsyou,weshould talkabouthowyouwantyourcomputertoboot.Doyouwantittogodirectlytoa graphicalenvironmentordoyouwantyourmachinetobootintotextmodewhereyou wouldthenissuethe'startx'command?Ifyouwantgraphicsmoderightaway,then youneedtohaveaprogramlikexdm,whichwillstartyourwindowsmanagerof choice,or'kdm'or'gdm'whichwillstartKDEorGNOME,twodesktopenvironments thatwe'lltalkaboutalittlelater. ThedecisiontostartupgraphicallyismadewhenyoufirstinstallLinux.Ifyoufound thatyou'vechangedyourmind;thatis,younowwanttostartupgraphicallyorvice versa,youcanusuallychangethiswithyourdistribution'stools.

132

Youcanchangethestartupbehaviorbygoingtoyour/etc/directoryandchanginga file.Thefilenamewilldependonyourdistribution.WithSuSE,forexample,itisthe filecalledrc.config.Youshouldchangetheline: DISPLAYMANAGER="" to: DISPLAYMANAGER="xdm" Youmayalsouse'kdm'or'gdm'here.MakesurethatyourCHECK_INITTABsetting is"yes" InthecaseofRedHatandRedHatbaseddistributions(Mandrake,KRUD),you'llneed tochangethefile/etc/inittab.Intheline:id:3:initdefault:,thenumber3needstobe changedtoa5 AsImentioned,ifyouwanttodojusttheopposite,changethedefaultgraphicallogin toatextmodelogin(somethingwhichIrecommend),justreverseallthosechanges above.Ifyoudecidednottouseagraphicallogin,youmaywanttouninstall'xdm' (orgdm/kdm). Well,nowthatwe'reclearonwhethertouseagraphicalstartupornot,let'sexplore someofthepossibilitiesforyourLinuxdesktop. Choosingthelookthat'srightforyou Inrecentyears,asLinuxhasbecomemorepopular,membersofLinuxcommunity havetriedhardtoshakeoffthereputation,whichIfeelhasalwaysbeenunwarranted, thatthegraphicaluserinterfaceforLinuxisatbest,boringandatworst, unmanageable.Thisisbasedon,ofcourse,comparisonswiththeuserfriendlinessof theomnipresentMSWindowsandthewelldeservedgoodreputationofthe MacintoshOSes.AfterusingWindows95from1995untiltheendof1997andtesting variousMacOSesextensively(atonepointusingMacOS8exclusivelyforone monthIwasstayingwithrelativesandneededtogetsomeworkdone),Icansafely saythatLinuxdoesn'tandprobablyhasn'thadareasontoenvytheothertwomajor OSofferingsintermsofgraphicinterfacessinceabout1998.Graphicuserinterfaces underLinuxarecomparablewiththeseotheronesinjustabouteverythingandeven enjoysomeadvantages.ThemajoroneoverMSWindowsis,ofcourse,stabilityand security.TheadvantageoverMacintoshisprimarilycostrelated. Ifyou'rereadingthis,thenyou'veprobablymadethedecisiontotryLinux.Beforewe talkaboutwhatyourLinuxdesktopisgoingtolooklike,weshouldfirsttalkaboutthe differencebetweenawindowmanagerandadesktopenvironment. Windowmanagers Mostprogramsmadeforcomputersnowadaysruninagraphicenvironment. However,itbecameapparentthattheseprogramswouldbemoreefficientifthey couldtaketheirattributesfromacommonsource.Thisiswhatawindowmanager does.Itdecideshowthewindowisgoingtolook,theaspectofitsbuttonsandframes. Itdetermineshowitisgoingtoreactedwhenyouclickinitoryoureduceitorresize it. TherearemoretwodozendifferentwindowmanagersavailableforLinux.Themore popularonesmaketheirwayontoLinuxdistributions.Theyrangefromcompletely minimalisttowellengineeredworksofart.Hereisalistoftheonesthatgenerally findtheirwayontothemajordistributions'CDs. 133

thefvwmfamily Blackbox IceWM Sawfish Enlightenment WindowMaker AfterStep Youcancheckouttheabovesitesandfindonethatyoulike.Thefirstone,FVWM,is mypersonalfavorite.Itisalsothemostminimalistoftheone'sI'velistedhere.This is,asfarasIknow,theoldestoftheaforementionedaswell.Thisisnotmeanttobe anendorsementofthiswindowmanager.Ijusthappentolikeitsminimalistapproach andlowmemoryrequirements.I'dratherpassthatRAMsavingsontothereally importantapplicationsrunningonmycomputer. Ihaveprovidedascreenshot(153k)ofthemyviewontheworldofLinux.*Ihavea menuitemthatlinkstoascriptthatwillplaceanewpictureasthedesktopimage whenIgetboredoftheoneI'vebeenseeingforacoupleofdays(orhours,depending onmythresholdofboredomatthemoment). Ihavefuntweakingtheconfigurationfile.Ithinkthemainreasonthatalotofpeople preferotherwindowsmanagerstofvwm2isthatthefilethatsetsupyourdesktop menusandbuttonsandotherthingshastobeworkedonbyhand.Theyreallyprefer theclickasyougoconfigurationofotherwindowmanagers.Ihappentolike experimentingandIampronetochangeitonceamonthorso(dependingonthat thresholdofboredomfactoragain).Fvwm2issoconfigurablethatifyougot5 differentconfigurationfiles,knownas.fvwm2rc,offtheInternetandtriedthemout, youwouldswearthatyou'reseeing5differentwindowmanagers. Youcancheckoutthe.fvwm2rcfilebehindtheabovescreenshot.I'dliketo acknowledgethatthemainfilewaswrittenbyJayKuri.ThanksJay,whereveryou are.IalsoincludedsometweaksthatIgothereandthere.Themainbuttonsyousee arefromEricS.Raymond's(authorofTheCathedralandtheBazaar).fvwm2rcand modifiedslightly. Ofcourse,everyoneisnotintotweakingandpreferamore"clickable"configuration. Perusetheofferingsoutthereandchooseonethatsuitsyourneeds.Youmayalso wanttoholdofonthewindowmanagersforabitandreadthenextsection.Wetalk aboutdesktopenvironments,theultimateuserfriendlyGUIexperienceforLinux.

*

There'saneatapplicationcalledgkrellmthatkeepstrackofalotofthingsthataregoingonwiththe systembesidesdisplayingthetimeanddate.MSWindowsusersshouldtakenoteoftheuptime(last timeofreboot)of27days,21hours.Wehadapowerblackoutthatlastedabout3hourswhilea transformerinmyneighborhoodwasbeingfixed.Previousuptimewas31days.Idon'trememberwhat happened31daysbeforethat.

Protectingtheenvironment Mostcomputerusersliketohaveasetoftoolsthattheyalwaysseethingslikea clock,aregionthatdisplaysthedate,abuttonthatdisplaysamenuwiththeprograms availableforyoutouse.Peoplehavebecomeaccustomedtoaniconsystemthatsits ona"desktop"thatallowsyou,withaclickofyourmouse,tohaveyourfavorite programupandrunningoropenawebbrowsertoyourfavoritewebsite.Thisusually 134

goesbeyondthecallofdutyforawindowmanager.Inthesecasesyouneedthe servicesofa"desktopenvironment".Thisisauniformlookingdesktopinterface whichsitsontopofandusestheservicesofawindowmanager.Therearetwomajor desktopenvironments,GNOME,whichusestheservicesofindependentwindow managers(atthetimeofthiswritingGNOMErunswithEnlightenment)orKDE, whichhasitsownbackgroundwindowmanager,knownaskwm GNOMEorKDE Thequestion:'ShouldIuseGNOMEorKDE?'wasacontroversialonenotsolong ago.Luckily,now,itisjustamatterofwhichinterfaceyoulikemore.The controversystemmedaroundtheKDEprojectwhichwasfoundedin1996withthe goalofcreatingauniformdesktopexperienceforLinux.KDEmadethedecisionto uselibrariestocreatethedesktopinterfacewhichwerenotopensource.Thelibraries inquestion,knownas'QT'arenowopensource,sothequestionisprettymuchmoot. However,atthetime,theissueinspiredayoungMexicandevelopernamedMiguelde IcazatocreateadesktopinterfaceknownasGNOME. GNOMEwasfoundedinAugustof1997andwasanattempttocreateauniform desktopmanagerthatwastotallycompliantwiththeGNU'sGeneralPublicLicense, avoidingthelicensingissuesinvolvedinthecaseofKDE'susingtheQTlibraries. MigueldeIcazaandNatFriedmanfoundedHelixCodein1999tooverseethe businessendofdevelopingtheGNOMEdesktop.HelixCodelaterchangedit'sname toXimian. WhatGNOMEandKDEcanoffer BothofthesedesktopenvironmentsofferaMicrosoftWindowslikeexperience.To date,KDEistheonlyoneofthetwotoofferanofficesuiteforwordprocessingand it'sownwebbrowser.Otherthanthat,bothoffertoprateproductivityapplications likeemailclients,agendaandschedulingsoftwareandaddressbooks.Theyoffer multimediasoftwareforplayingCDs,MP3sandothermusicformats.Bothoffera largeselectionofgamesinadditiontoothersundryapplicationsforsystem monitoringandothermiscellaneoustasks. Wheretogetthesedesktopenvironments MostdistributionscomewithboththeGNOMEandKDEdesktopenvironments. However,ifyourdistributiondidnothavethisoryouarereadingthisandhavenot yetinstalledLinux,youmaywanttocheckoutbothofferings. KDEhomepage XimianInc. Youcanalsodownloadthelatestversionsfromtheirhomepages. Popular,usefulandimportantprogramsthatruninXWindow Atthispointyou'vechosenyourwindowmanagerand/ordesktopenvironment. Regardlessofthe"look"you'vechosen,youhavetohaveprogramstorun.Youneed applicationstosurftheInternet,writeemail,manageyourfiles,writelettersanda thousandotherthingsyouwanttodo.TherumorsyouhearaboutLinuxlacking applicationsornotbeingableto"makeitonthedesktop"arefalse.Thereisnomajor applicationthatacomputeruserneedsthatLinuxlacks. Internet/WWWBrowsers NetscapeCommunicator 135

TheheavyweightofallbrowserswasoneofthefirsttoreleaseaversionforLinux. IncludesanHTMLauthoringtoolandfullfeaturedemailprogram.Comeswiththe standardpluginstoviewFlashanimationandlistenandseeRealAudio/Video content.Atthetimeofthiswriting,version6.2isavailableforLinux. Opera Billedasthe"fastestbrowser",OperaSoftwareofNorwayreleasedtheirfirstversion ofOperaforLinuxinMarchof2000.Theseearlyversionswerenotstablebutthe companykeptworkingandreleasedafinishedOpera5forLinux.Atthistime,the companyhasreleasedabetaversionOpera6whichofferspluginsupportforFlash andRealAudio/Video.TheirbrowserforLinuxstilldoesn'thavethesamefeaturesas theirflagshipMSWindowsversion(likeanemailclient),butit'sfastandextremely stableandreliable. Mozilla MozillaistheopensourceversionofNetscape.Itisalmostidenticalbutthepeoplein theMozillaprojecthaveaddedsomeextrastoitthatgiveitabitofanadvantageover its"brother",Netscape,likebeingabletoopennewtabs(likeOpera)insteadofonly havingtheopentoopennewwindows.Ifyoudon'tlikeclutteringupyourdesktop, thisisawelcomefeature.Italsocomeswithallthesupportforplugins,Javaand JavaScriptthatNetscapehasplusthesameemailclientandHTMLauthoringtools.It alsoadsandaneasytouseIRC(InternetRelayChat)clienttoitsextras.Atthetime ofthiswriting,theMozillaprojectisjustabouttoreleaseversion1.0.It'sbeenalong timecoming,butiftheoldadage:Slowandsteadywinstherace,theymaywinthe browsercontest. Konqueror Konqueror,partoftheKDEproject,isafilemanagerandInternetbrowserwrapped upintoone.Youcansurfthenetandmanageyourfilesatthesametime.Ifyou're migratingfromWindows,youshouldfinditverysimilartoMicrosoft'sInternet Explorer.IncludespluginsupportaswellasenablingforJavaandJavaScript.You needtohaveKDEinstalledtorunthis. Galeon GaleonisthebrowserassociatedwiththeGNOMEproject.ItisbasedontheGekko HTMLrenderingenginethatalsorunsMozilla(thisconvertsHTMLintocontentyou canread).ThisbrowserisessentiallyMozilla(youactuallyneedMozillatorunit) modifiedsomewhattofitintotheGNOMEschemeofthings.Withtheuseof'themes', thelookismuchmoreconfigurablethanMozillaitself. StarOffice We'lltalkmoreaboutStarOfficeinoursectiononofficesuites.Itcomeswithawitha webbrowserandanemailclient. Speakingofemailclients,let'slookatsomepopularonesavailableforLinux Emailclients Theprogramyouusetoget,writeandsendyouremailisoftenreferredtoasa "client".Thisistodistinguishitfromtheprogramsthatsitonserversthatreceiveand processemailseithersenttoorsentfromyou.Emailhasbecomesoimportantinour everydaylifethatIhaveobservedthatadvocatingoneemailclientoveranotheroften 136

takesonafervorusuallyassociatedwithreligiousbeliefs.Herewe'lllookatsomeof themajoremailclientsforLinux. Evolution Ximian'sEvolution,partoftheGNOMEdesktopprojecthasreceivedalotofpress lately.ItisshapinguptobetheonlyseriouschallengertoMicrosoftOutlook's dominationofthegroupwarescene.SeeingthatithasallthefeaturesofOutlook,sans thevirusproblem,thenyoucanseewhyit'sgettingsomenotice.Ifyou'relookingfor agoodemailclientthatcomeswithschedulingtools,taskmanagement,addressbooks andallthosethingsthatthebusyyetorganizedpersonneeds,thanXimianisprobably thethingforyou. Kmail KmailisKDE'smajoremailclient.Itisnotacompletegroupwaresolutionlike Ximian'sEvolution,butitsemailmanagementcapabilitiesareverypowerful.Thereis supportforallmajortypesofemailtransport,intricateconfigurationofmailfilters, completesupportforHTMLformattedmailandotherusefulfeatures. Sylpheed JapanesedeveloperHiroyukiYamamotohasdevelopedthisfast,easytousefull featuredemailclient.Thisclientisabighitwithdevelopersasitoffersreallynice threading(theabilitytokeeptrackofallmailsbasedononeoriginalmail)andafairly goodwayofmanagingdifferentemailaccounts.Ifyouhavetorespondtomailin differentcapacities(boss,friend,worker),Sylpheedoffersthetoolstodothisallin oneclient. Mutt OneofthemostfamousquotesintheLinuxworldistheonefoundatthetopofthe homepageforMutt:Allmailclientssuck.Thisonejustsucksless..Thiswassaidby MichaelElkins,whodevelopedthisemailclient.Alotofpeoplewillprobablypoint out,andrightlyso,thatMuttdoesn'thaveagraphicuserinterface.Thatistrue. However,thisclientissopopularintheLinuxworldthatIjusthadtoincludeithere. IfyouareanewcomertoLinux,youmaynotwanttouseMuttjustyet.Usingit efficientlyrequiresawellwritten.muttrcfile.Thisisthemainconfigurationfilethat determineshowMuttisgoingtowork.However,ifyougetusedtoMutt,youare probablynotgoingtoeverswitch.It'slackofaprettyinterfaceismorethanmadeup forbytheabilityyouhavetoconfigureMutt.Afteryouhavesomemonthsbehindyou workingwithit,emailswillpracticallywritethemselves.Ifyouhandlealotofemail, thisistheclientyouprobablywanttoatleastlookinto. Officesuites,wordprocessorsandspreadsheets StarOffice StarOfficeisacomplete,fullfeaturedofficesuiteontheideaofMicrosoftOffice.It comescompletewithwordprocessor(ofcourse),spreadsheet,databaseinterfacing, presentationsoftwareplusitofferswebbrowsingandemailandafewotherfeatures. OriginallydevelopedbyStarDivision,StarOfficewasacquiredbySunMicrosystems in1999.Thecurrentstableversionofthissuiteis5.2atthetimeofthiswriting. However,SunhasannouncedthattheyplantochargefordownloadsofStarOffice version6. KOffice 137

KOfficeistheKDEProject'sofferingfordesktopproductivity.Itincludesallofthe standardofficesuiteapplications.Thesoftwareisofferedfreeofcharge. VistaSource'sAnywhereDesktopforLinux ThissuitewasformerlyknownasApplixWare.Onceagain,allthestandardoffice suitetoolareofferedhere.ThisoneboastsaMicrosoftOfficelookandfeel.Thisis notafreeproduct.Itcost99USdollarsatthetimeofthiswriting. SiagOffice Don'tletanamelikePatheticWriterdissuadeyoufromcheckingoutthisofficesuite forLinux.ThewordprocessorpartofthesuitecanopenMicrosoftWordformat (*.doc)files.TheprojectstartedwiththeSchemeinagridspreadsheet.Nowyou knowwhyit'scalledSiag.Anotherfreeofferingintheofficecategory. HancomOfficeforLinux HancomLinuxofKoreahasdevelopedthiscommercialfullfeaturedofficesuitefor Linux.ProvidescompatibilitywithMicrosoftOfficeformatsandsmoothintegrating intotheKDEdesktop.Anevaluationversionisavailablefordownload,butthe softwaremustbepurchasedinordertocontinuetouseit. GNOMEOffice GNOMEofficeshouldactuallyappearinquotes,becausethisisnotanofficesuitein theclassicsense,butasetofapplicationsthatareoftenassociatedwithofficesuites, asapackagedeal,sotospeak.Someofthehighlightsinclude: Gnumeric,aspreadsheetapplication AbiWord,awordprocessor(itevenrunsunderWindowsandMacOS) Gnucash,apersonalfinancemanager GNOMEDB,databaseconnectivitysoftware IfyoudownloadtheXimianDesktop,you'llgettheseapplicationsplustheother productivitytoolsassociatedwiththeGNOMEproject.Littlegoodiestoimproveyour qualityoflife (aka:thoselittleappsyou'drathernotlivewithout) Music WhenIgotbroadbandInternetaccess,mylifechangedforever.Nomorepayingfor dialupsonahourlybasis.Nomorepainfuldownloadsofsoftware.Butwhat'smore importantthanallofthisisthatIcouldnowlistentoradio!Sowhat,yousay.Well,I livemorethan6,000milesfromtheplacewhereIgrewup,sowhenIcouldfinally listentoaradiostationfromthecitywhereIwasbornaseasilyasmymother(who stilllivesthere)canswitchontheradio,Iwasdelighted.RealAudioplayerforLinux isjustoneofthoselittleappsI'drathernotlivewithout. RealPlayer Ican'thelpbutmakeaneditorialcommenthereaboutthisapplication.Thisforme representsmorethanjustawayoflisteningtoyourfavoriteonlineradiostationor viewingtheBBCWorldServicebroadcast.RealPlayerrepresentsthedifference betweenstationshavingachoiceto"webcast"freelyorhavingtokowtowto Microsoft.ItlookslikeGatesandCo.plansondominatingtheonline music/informationindustry.RealNetworksisatthispointtheonlythingpreventing themfromdoingit. 138

NowthatI'vefinishedmyeditorializing,youcangogetRealPlayerforLinuxand installitandstartlisteningtowebbroadcasts. XMMS XMMSstandsfortheXmultimediasystem.Ifyou'refamiliarwithWinAmp,you'll havenotroublegettingusedtothisprogram.YoucanlistentoyourfavoriteMP3s plusfilesinthenewlyemergingfreeOggVorbisformat. Imageviewingandediting TheGIMP GIMPstandsforGNUImageManipulationProgram.Itshouldneverbeassociated withtheEnglishwordmeaninglame.Gimpalsohasanothermeaning,accordingto thedictionaryIconsulted:Smart;spruce;trim;nice.That'sabetterdescription.This isafullfledgedimagecreatingandretouchingapplication.Youcanapplyallsortsof filtersandevenwritescriptsfordoingthingstotheimagesautomatically.Ifyouwork alotwithimagesandthinkthatbyswitchingtoLinuxyou'llbeunabletowork efficientlywithgraphics,thencheckoutTheGIMP.You'llbepleasantlysurprised. xv Inthewordsoftheitsauthor,JohnBradley,xvdoesn'tstandforanything.Iusethis programallthetime,literally.ItiswhatIusetodisplaytheimageinmydesktop window. typethis: xvrootmaxquityour_favorite_pic.jpg andxvwilldisplayyourfavoritepictureasthepiconyourdesktopSometimesIget boredandIusethisscripttorotatemyfavoritepictures. #!/bin/sh foriin`ls/home/mike/rotation_bkg/*.jpg` do xvrootmaxquit$i sleep300 done Ifyou'relookingforheavydutyimagesoftware,xvisnotit,however.Thisisthe author'sownwords:
Basically,xv'sprimarythrusthasalwaysbeendisplayingimages(inmanyformats)quicklyandnicely onawidevarietyofdisplayhardware.

Thatprettymuchsumsitup.xvisdistributedasshareware. ImageMagick ImageMagickisasuiteoftoolsfordisplayingandmanipulatingimages.It'snotas powerful(inmyopinion)asTheGIMPbutmorepowerfulthanxv.Iuseitforthree basicthings.The'display'toolIusetotellmyemailclientopenimagesthatpeople sendmeinemails.AnotheroneIusealotisthethumbnailgenerator.Ifyou'vegota lotofimagesinadirectoryandyouwanttohaveaninventoryofallofthemasone image,thenyouwouldtype: display'vid:*.jpg'

139

Thiscreatesoneimageofallofthejpgimagesasthumbnailsinthedirectoryyou're in.ThistakesupalotofCPUpoweronevenafairlypowerfulmachine,sobepatient. Ifyou'vegotalotofimagesinadirectoryandaslowmachine,youmightwantto considerdoingtheminsmallbatches. ThisnextuseofImageMagickismytwoyearold'sfavorite.Ihavesomepicturesof himinadirectoryandItype:


animate*.jpg

Thisstartsupaslideshowofhimatblindingspeedandhegetsabigkickoutofit.If youwanttogettheimagesrotatingatamoremanageablespeed,justusetheshift> keysorclickwiththerightmousebuttontocallupthemenu. Texteditorsandviewers Sometimesyoudon'twanttofireupawholeofficesuitetoreadsometextfileand sometimesyouhavetocreateand/oreditdocumentsasplaintext.Ifyouwanted,for example,tomodifymyimagerotationscriptabove,youwouldopenupatexteditor. TherearetwothatIuseontwodifferentoccasions. Emacs ThereisaversionofEmacsifyournotusingXwindowandthenthere'sXEmacs,a versionexpresslywrittenforXwindow.IrefertothexwindowversionofEmacs, whichisliketheconsoleversion,buthasclickablemenusandwindowsand everythingyouneedtoworkinagraphicalenvironment.RichardStallman,founderof theGNUproject,firststartedworkingonEmacsin1974.Ithassincethenbecomethe flagshipapplicationoftheGNUproject.Itistrulytheperfectapplicationtobetheone associatedwiththeGNU.ItisaSwissArmyKnifeofeditors.Tocallitan'editor'is toinsultitsomewhat.Itdoesalittlebitofeverything.Tome,it'salmostlikeamini operatingsysteminandofitself.Ifyou'reaprogrammer,Emacsisessentialfor working.IfIcouldnotuseEmacsforsomereason,Iwouldprobablygooffandherd sheep.(andifyouthinkI'mjoking,askmywife).EvenfornonprogrammingtasksI useit.TheentireLinuxOnlinebeginners'course(yes,thewordsyouarereadingright now)werewrittenintheirentiretyusingEmacs.Thatdayin1974whenRichard StallmansatdownandstarteddevelopmentofEmacsisagreatdayinhistory. xedit xeditisabasictextviewer/editorforXwindow.Itwasoneofthefirstapplications.It isnotslickorfancy,butthereisonethingIlikeverymuchaboutit.Theabilitytofire itupfromanxtermwithacoupleofpreferencesofmine.Readingfairlylongthings onacomputerisnotoneofmyfavoriteactivities.Myeyesdon'tseemtolikeiteither. Withxedit,youcanspecifyareadablefontandsomegoodeyefriendlycolorswhen youstartitup. xeditbgseagreenfgnavajowhitefn9x15*boldsome_text_file.txt& Aswe'reonthetopicofbasicXWindowapplications,youcanusexcolorstogeta backgroundandforegroundcombinationthatsuitsyoureyes.Usetherightmouse buttontoselectafontcolorandthemiddlebuttontoselectthebackground. Ifyouwanttoselectcolors(forexample,forwebpagework)andyou'vegotthe GNOMEdesktopinstalled,youcanuseGNOMEColorBrowser.It'seasierto managethatxcolorsandhasanicegrabfeaturetoselectcolorsfromotherplacesand gettheirvalues/names. 140

MiscellaneousPrograms roottail tailisaconsoleapplicationthatisnormallyusedformonitoringfilesthatchange constantly,likelogfiles.roottailcanbeusedtodisplaythesefilesonyourdesktop whileyou'rerunningXwindow.Inormallyusethistorememberimportantstuff.It reallycomesinhandy.First,youshouldcreateatextfilewithyourfavoriteeditor. Callit'reminders'.Thenoneachline,writesomethingthatyouwanttoremember. Then,yourunroottail.It'sbesttodothiswithafewoptions.Forexample,thisis howIrunit: roottailcoloryellowfont12x24shadeg+10+100$HOME/reminders& Let'sexplainsomeoftheseoptions.First,after'color'youshouldusethenameofthe coloryouwantthetexttoappearin.Usexcolorstofindacoloryoulikethat's supportedbyyoursystem.Thenextoneis'font'.Asyousee,I'vechosenagoodsized one.'shade'willgivethetextalittleshadeunderitandwilllooksnazzier.'g'stands for'geometry'orthelocationinthewindow.Iuse+10+100whichsetitrightinfront ofme.Youcanexperimentwithsettings.Nowyouhavenoexcuseforforgettingto buyyourlovedonespresentsontheirbirthdays! gkrellm Thisisnicelittleapplicationtomonitorwhat'sgoingonwithyourcomputer.Youcan keeptrackofyoumemoryusage,swapspace,howmuchbandwidthyou'reusing throughyourethernetcardandmuch,muchmore.Youcanseeitinthisscreenshot. It'srunningontheupperrightsideofmydesktop.It'susefulasawaytoalertyouto howmanycluelessWindowsusersthereare.Invariably,whensomeSircamprovoked mailcomesthrough,the'eth0'monitor,whichchecksbandwidthusagewillstartrising fornoapparentreason.IfyoudoconversionsofaudiotoMP3orOggformat,youcan watchyourCPUusagegooffthescalewhenyoudothem.Placeyourmouseover gkrellmandpressF1toconfigureothermonitors.Therearealsopluginsand themes/skinsavailable. Xchat xchatisacomfortableIRC(InternetRelayChat)client.It'sveryeasytoconfigureto yourliking.ThereisthepossibilitytousePythonandPerlscriptstoautomatesome thingsyoudo. Alotofprogramstochoosefrom TherearethousandsofprogramsforLinuxinourapplicationssection.Havealook andwe'resureyou'llfindtherightprogramstosuityourneeds TipsandTricksforXWindow .xinitrc Thisisafileyou'llfindinyouruserdirectory.Youcanuseittostartprograms automaticallywhenyoustartXwindow.Openthefilewithviorthetexteditorof yourchoosing.Then,forexample,add: xclockbgwheatgeometry100x100+1+1& bgsetsthebackgroundcolorandthegeometrysettingIhaveusedheregivesyoua fairlysmall,butnottoosmallclockintheupperlefthandcornerofyourdesktop.You cantype:manxclocktoseemoreoptions.Experimentwithoptionsfirstbeforeyouput

141

yourdefinitivexclocksettingsinyour.xinitrcfile.Justtypeyoursettingsintoan xtermandtrydifferentones.Type:killallxclocktoshutofftheclockeachtime. .Xdefaultsfile There'sanotherfileinyouruserdirectorycalled.Xdefaults.Youcanusethisfileto changethewaysomeofyourXwindowapplicationslook.It'sfuntotryoutdifferent stylesandgetsomesettingsthatpleaseyoureye.Beforeyoutrytodothishowever, makeabackup.Type: cp.Xdefaults.Xdefaults_good becausethereisalwayssomedangerofmakingsomeapplicationsnonoperable becauseyouhaveleftspaceswhereyoushouldn't.Itisimportantwhenyouchange settingsthatyouleavenotrailingspaces.Mostmajordistributionsprovideaworking. Xdefaultsfile.It'sbesttoleavewhatyoufindthere,butyou'refreetoaddstufftoit. Asanexample,let'schangethelookofemacs,forexample. First,openupthefilewithVioranytexteditoryourprefer.Addthistoit: !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !!emacschanges[date] emacs*Background:DarkCyan emacs*Foreground:Khaki !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Let'sexplainwhatwe'vedonehere.First,theexclamationpoint(!)inthisfileisused tomakecomments.ThetworowsofexclamationpointsI'veusedtoshowwheremy emacssectionbeginsandends.ThenIusetwotocommentthatIamchangingemacs andIhaveincluded[date]whereIwouldputtheactualdatetoshowwhenImadethe changes.Youdon'thavetotothis.It'sjustsomethingextratoremindmewhenImade thechanges.Thenwemaketheactualchanges. With:emacs*background:DarkCyanwecanchangethebackgroundoftheapplication's menubarandframe.Youcanuseanycoloryoulikethatthesystemsupports. With:emacs*Foreground:Khakiwe'vechangedthecolorofthewordsinthemenu. Tomakethechangestakeeffect,youhavetoissuethiscommandinanxterm: xrdbmerge$HOME/.Xdefaults Thiswillrestartthexserverdatabaseandloginyourchanges.Ifyoudon'tdothis,X windowkeepsyourold.Xdefaultsinmemoryandyouwon'tseeanythingnew. Restartemacsandyoushouldseeyournewcolors.Ifemacsdoesn'tcomeup,you mayhaveleftsometrailingwhitespace.Ifthatisthecase,justtypeemacsinanxterm andanerrormessageshouldappearsayingsomethinglike:Warning:Colorname"khaki" isnotdefinedorsimilar.Ifyouseeaspacebeforethesecondquotationmark,then you'vegotwhitespaceinyour.Xdefaultsfilethatneedstobeeliminated. Asyougetmoreadeptatchangingthings,you'llmakeyourdesktopmoretoyour liking. xwininfo Ifyou'reinterestedinseeingabitofinformationaboutcertainprogramsrunning,you cantypexwininfointoaterminalandthenclickonanywindow.Forexample,Ihad anotherxtermopenandIclickedonitandgotthisinfo: xwininfo:Windowid:0x2c0000e"xterm" 142

AbsoluteupperleftX:211 AbsoluteupperleftY:132 RelativeupperleftX:0 RelativeupperleftY:0 Width:581 Height:340 Depth:16 VisualClass:TrueColor Borderwidth:0 Class:InputOutput Colormap:0x20(installed) BitGravityState:NorthWestGravity WindowGravityState:NorthWestGravity BackingStoreState:NotUseful SaveUnderState:no MapState:IsViewable OverrideRedirectState:no Corners:+211+1328+1328128+211128 geometry80x243+109 Thiscomesinhandyespeciallytofindsuitable'geometry'settingsforuseinstarting upapplicationsandincludingtheminthe.xinitrcfile. xset Thisisacommandlineutilitytocontrolthingslikeyourmouse,keyboard,monitor andpcspeaker.BothGNOMEandKDEhaveothergraphicappstodothisstuffalot easier,soIfindmyselfusingthislessandless.Butyoucantryitout.Forexample, type:xsetbofftostopyourcomputerfrombeepingatit.Andtoturnitbackon?You guessedit:xsetbon.Youcanalsochangethetonebytypingsomethinglike:xsetb30 550300Thefirstnumberisforvolume,thesecondpitchandthethirddurationofthe beep. xsetroot Inaprevioussection,wetoldyouhowtousexvtoputyourfavoritepictureonyour desktop.Ifyougettiredofpicturesandyouwantsomethingplain,youcanuse xsetroottojustputacolorschemeonthedesktop.Forexample,typing:xsetrootsolid seagreenwillgetyouasoliddarkgreencolorasabackground.Thisoneissoothingto theeyes.It'sthesamecolorusedonpoolandcardtables.Ofcourse,you'refreetouse thecoloryoulike!Type:manxsetroottoseeotheroptions. MoreXWindowTipsandTricks StartingXonothervirtualterminals WithLinux,youarenotlimitedtostartingXwindowonlyonce.Youmayopenup anothervirtualterminalandstartanotherinstanceofXwindow.Rememberthough thatrunningtwoinstanceswilluseupalotofmemory. Aswesawinpreviouslessons,toswitchtoanothervirtualterminal,press: CTRL+ALT+F2(orF3uptoF6) Thenloginasanotheruserandtype: 143

startx:1

YoucanswitchbetweeninstancesofXWindowbytyping: CTRL+ALT+F7and CTRL+ALT+F8 UsingtheXWindowprogramsfromanothercomputer ThisisthethingIlovetoshowpeoplefromtheMSWindowsworld.Ipointtothe computeracrosstheroomandthensay:"NowIamgoingtostartthebrowserfrom thatsystemandmakeitappearhere."Youdon'tneedtobeDavidCopperfieldto performthismagic.YouonlyneedXwindowrunningononeandinstalledonthe other.Youalsoneedameansofloggingintotheothercomputer.Andhere'sone morething.Thecomputerdoesn'tevenneedtobeinthesameroom.Itcanbeina differentroominadifferentbuildingonadifferentcontinent.Providingyour bandwidthisgoodenough,youcanstartaprogramonacomputer5000kilometers awayanduseitonyourdesktop. Therearetwowaystodothis.Oneisnotsecureandprobablyshouldonlybeusedon alocalnetwork,ifatall.Thesecondoneisverysecureandcanbeusedfortrans oceanicXwindowsessions. Ifyouhavetheremotelogindevicetelnetandthetelnetserverinstalledonthe machines,youcanusethisfairlysafelyinalocalnetwork.Forexample,ifyou workstationiscalled'amos'andtheothermachineiscalled'andy'andyouwanttouse aprogramon'andy',sittingat'amos',youwouldtype: xhost+andy Thenwithtelnet,logininto'amos'(telnet>openamos) Then,type: DISPLAY=amos:0.0 then exportDISPLAY Nowyoucantypethenameofanyprogramyouwanttorunthatyouknowison 'andy'.Rememberthough,asImentioned,telnetisinsecure.Thisarebetterwaysof doingthis.Youshouldneverdothisifyou'reworkingoverapublicnetwork,likethe Internet. RemoteXsessionswithOpenSSH OpenSSHstandsforOpenSecureShell.That'sjustwhatitis.Asecureshellfor logginginatothercomputersinasecuremanner.Whatgoesoverthenetworkis encryptedandyoursecurityisnotcompromised.Mostmajordistributionswilloffer thisanditisnormallyinstalledbydefault.Youmayhavetospecificallyinstallthe OpenSSHserverwhichyouneedtohavetoforthistoworkonyourlocalnetwork. UsingXonanothermachine,alsoknownasXforwardingisusuallydisabledby defaultsoyoumayhavetoeditonefiletogetthistoworklocally.Ifyou'redoingthis acrossoceansorcontinentstheconfigurationwilldependontheremotemachine.As longasyouhaveaOpenSSHclientandanaccountontheothermachine,youcando this. AsImentioned,ifyouwanttodothislocally.Here'swhatyouhavetodo.Let'suse our'amos'and'andy'exampleagain.You'resittingatyourworkstationcalled'amos'. MakesureyouhaveOpenSSHserveroninstalledon'andy'andhavecreatedauser 144

accountthere.On'andy'youneedtologinas'root'andmakesurethatthereisalinein afilecalled'sshd_config',usuallylocatedin/etc/sshthatsaysX11Forwardingyes.Ifthis saysX11Forwardingnothanyouneedtochangeittoyes.Thenyouneedtorestartthe OpenSSHserver.TheeasiestwayistolookforitsPIDbytyping:psax|grepsshdand killingit'sPIDnumber.Thentype:sshdtostarttheserveragain. Then,from'amos'justconnectto'andy'viaSSH,likeso: sshl[yourusername]andy you'llbeaskedforyourpassword.YouloginandthenyoucanruntheXapplication thatyouwant.Itwillcomeuponyourdesktopon'amos'courtesyof'andy'.Afinal wordaboutXwindow TheGUIapplicationsforLinuxarealwayschanging,evolvingandadaptingtouser needs.Linuxhascomealongwayinthepastfewyears.Itisbecomingaserious threattothedominanceofMicrosoftWindowsnotonlyintheservermarketbuton thedesktopaswell.TheimportantworkdonebythepeopleintheGNOMEandKDE projectsaswellasotherthosecarryingoutdevelopmentofotherwindowmanagers andXFree86showthelevelofcommitmentthereistogettingLinuxonthedesktops oftheworldscomputersinofficesandhomes. Inthislessonwe'vegivenyouanumberofaddressesofwebpagesofthesetypesof projects.Thebestthingtodotosupporttheseeffortsistocheckbackonthese projectsfromtimetotime,installthelatestversionandtalktoyourfriendsabouthow goodyouthinktheyare.Also,contactthedevelopersorjointhemailinglistforthat particularprojectandprovidefeedback,bothpositiveandnegative,aboutthesoftware you'vetried.That'sessentiallywhattheLinuxmovementisallabout.Youcanalso volunteertodosomework.Youdon'thavetobeaprogrammertomakeavital contribution.Youcantranslatethedocumentationorthegraphicinterfacetoyour nativelanguage,forexample.Intheend,anyformofcollaborationisgood.That's howLinuxgrewintothemajoroperatingsystemthatitisandthat'sessentiallywhat theLinuxmovementisallabout. LessonTwenty Theendofthebeginning ThisistheendofGettingStartedwithLinux,ourbeginner'sintroductiontothis operatingsystem.Whatwehaveintendedtodoistakeyoufromthepointwhere you'vegotsomeLinuxCDsandacomputerinfrontofyouwithoutLinuxinitto whereyou'veinstalledandandyou'reusingitproductively.Thismeansthatyou're usingittomaintainfiles,writedocuments,managedata,keepfiguresstraightwitha spreadsheet,surftheweb,writeemail,chatwithfriends.Atthesametimeyou're listeningtoyourfavoritemusicineitherMP3orOggformat,onaCDorstreaming overRealAudio. ThefactisthatthereisanendlessamountofthingsthatyoucandowithLinux.Our aimherewastogiveyouthebasics.Nowit'suptoyoutoexploretotryexpanding onthethingsthatyou'velearnedhere.Intheend,thepointistolearnandtohavea littlefunintheprocess. Wheredoyougofromhere? Atthistimewe'reworkingonourIntermediateLinuxCourse.Thiscourse,whichis stillindevelopment,willtakeyoufromthebeginnerleveltothepointwhereyoufeel 145

verycomfortablewithLinux.Ouraimisnottomakeprofessionalsystems administratorsoutofthosewhofollowthecourse,buttomakeyouindependent enoughwithyourLinuxmachinethatyoudon'tneedtoseekoutsidehelpas frequentlyasanovicedoestosolvetheoccasionalproblemsthatarise.Hereareafew ofthetopicsthatwe'llbecoveringinthenextcourse. generalsystemadministration securityalerts Linuxkernelcompilingandinstallationofnewkernels automatingservicesandtasks useofBashandPerlscripts firewalls settingupawebserverwithApache settingupamailserverwithsendmail SambaforWindowsfilesharing ProfessionaldatabasesMySQLandPostgreSQL Linuxforthesmallbusiness Ifyouarearegistereduser,we'llkeepyoupostedonupdatesastotheavailabilityof theIntermediateLinuxCourse.Ifyou'renotregistered,allyouhavetodoissignup andyou'llreceiveournewsletterwithupdates.

Author'sNotes HelloandwelcometotheBeginner'sGuidetoLinux.Iamtheauthor,MichaelJordan. IamalsothewebmasterofLinuxOnline.Aswasmentionedontheintroductionpage, Iwelcomecomments,suggestionsandwellintentionedcriticism.I'daskyoutotakea lookatwhat'sbelowbeforesendingoffanemailaboutanythingtodowiththecourse. Youmayhavefoundyourquestionansweredbelowandwillsaveusbothsome typing.(oryourwonderingwhyyoudidn'tgetaresponse). Historyofthecourseandrationale Inthespringof2000,MichaelMcLagan,ownerandGeneralManagerofthiswebsite, broughtuptheideaofdoingvariousLinuxcoursesofdifferentlevelstobeoffered freeofchargetothepublic.Initially,thistaskwastobehandledbyoneoftheweb developers.Unfortunately,thispersonhadtobeletgo.Thetaskthenfelltome. IearnedaB.A.inhistoryandteachingcertificationin1987andhavebeena practicingclassroomteachersincethen.Ihavewrittenonlineinstructionalmaterials forteachingEnglishasaforeignlanguageaswell,sowhenIgotthenodtodevelop thecourse,Iwasswimminginfamiliarwaters. OurdeadlinetogetthecoursepublishedwastheLinuxWorldExpoofAugust2000 inSanFrancisco.Some'backend'Perlscriptswereputintoplaceaboutamonth beforethiseventtohandleboththeauthoringofthecourseandthepublic'saccessto thematerial.ThedeveloperofthescriptsalsoleftLinuxOnlineandthesystemproved toodifficulttoworkwith.Withoutthedeveloperhereanymore,wedecidedtoswitch overtobasicHTMLformat.Byearly2001,accesstothefirstpartofthecoursewas

146

providedbyPerlscriptswhiletheremainingpartwasbeingofferedinstaticHTML files. Inthefallof2002,wedecidedtoendthishybridsystemandconverteverythingtothe HTMLformatexclusively.ThiswascompletedinJanuary2003.Ialsotook advantageoftheformatchangetototallyrewritesomesectionsandtobringthe courseuptodateingeneral. PlansfortheFuture ThecourseisnowbeingofferedfromstaticHTML,butasthecontentiswhatmatters, wecanadaptthetextinthesefilestoafuture'dynamic'contentmanagementsystem. Thissystemwillmakenavigationeasierandwillletusalsooffertestsandquizzes. Gradesonthesewillbeenteredintoregisteredusers'accounts.Oncethesystemisin place,wecanthenoffercertificatestothosewhohavefollowedthecourse.

147

Das könnte Ihnen auch gefallen