74
Unix Basics Kirrily Robert Training Co-ordinator Netizen Pty Ltd

Unix Basics - UNAM

  • Upload
    others

  • View
    8

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Unix Basics - UNAM

Unix Basics

Kirril y Rober tTraining Co-ordinator

Netizen Pty Ltd

Page 2: Unix Basics - UNAM

Unix Basicsby Kirrily Robert

Copyright© 1999-2000by NetizenPtyLtd

OpenPublication License

Thiswork (Netizen"Unix Basics"trainingmodulenotes)is licensedundertheOpenPublicationLicense.

LICENSE

TermsandConditionsfor Copying,Distributing, andModifying

Itemsotherthancopying,distributing,andmodifying theContentwith which this licensewasdistributed(suchasusing,etc.)areoutsidethescopeof this license.

1. Youmaycopyanddistributeexactreplicasof theOpenContent(OC)asyou receive it, in any medium,providedthatyou conspicuously andappropriatelypublishon eachcopyanappropriatecopyrightnoticeanddisclaimerof warranty;keepintactall thenoticesthatreferto thisLicenseandto theabsenceof any warranty;andgive any otherrecipientsoftheOC a copyof thisLicensealongwith theOC.You mayat your optionchargeafeefor themediaand/orhandlinginvolvedin creatinga uniquecopyof theOCfor useoffline, you mayat your optionoffer instructionalsupportfor theOC in exchangefor a fee,or you mayatyour optionoffer warrantyin exchangefor a fee.Youmaynotchargea feefortheOC itself. You maynotchargeafeefor thesoleserviceof providing accessto and/oruseof theOCvia a network(e.g.theInternet),whetherit bevia theworld wideweb,FTP, or any othermethod.

2. Youmaymodify your copyor copiesof theOpenContentor any portionof it, thusforming worksbasedon theContent,anddistributesuchmodificationsor work underthetermsof Section1 above,providedthatyoualsomeetallof theseconditions:

a) Youmustcausethemodifiedcontentto carryprominentnoticesstatingthatyouchangedit, theexactnatureandcontentof thechanges,andthedateof any change.

b) Youmustcauseany work thatyou distributeor publish,thatin wholeor in partcontainsor is derivedfrom theOC orany part thereof,to belicensedasa wholeatno chargeto all third partiesunderthetermsof this License,unlessotherwisepermittedunderapplicableFair Uselaw.

Theserequirementsapplyto themodifiedwork asa whole.If identifiablesectionsof thatwork arenotderivedfrom theOC,andcanbereasonablyconsideredindependentandseparateworksin themselves,thenthisLicense,andits terms,do notapplyto thosesectionswhenyoudistributethemasseparateworks.But whenyoudistributethesamesectionsaspartof a wholewhich is a work basedon theOC,thedistribution of thewholemustbeonthetermsof this License,whosepermissionsfor otherlicenseesextendto theentirewhole,andthusto eachandeverypartregardlessof whowroteit. Exceptionsaremadeto this requirementto releasemodifiedworksfreeof chargeunderthis licenseonly incompliancewith Fair Uselaw whereapplicable.

3. Youarenot requiredto acceptthis License,sinceyouhave notsignedit. However, nothingelsegrantsyoupermissionto copy, distributeor modify theOC.Theseactionsareprohibitedby law if youdo notacceptthisLicense.Therefore,by distributing or translatingtheOC,or by deriving worksherefrom,you indicateyour acceptanceof thisLicenseto do so,andall its termsandconditionsfor copying,distributing or translatingtheOC.

NO WARRANTY

4. BECAUSETHE OPENCONTENT(OC) IS LICENSEDFREEOFCHARGE,THEREIS NO WARRANTY FORTHE OC,TO THE EXTENT PERMITTEDBY APPLICABLE LAW. EXCEPTWHEN OTHERWISESTATED INWRITING THE COPYRIGHTHOLDERSAND/OR OTHERPARTIESPROVIDE THE OC"AS IS" WITHOUTWARRANTY OFANY KIND, EITHER EXPRESSEDORIMPLIED, INCLUDING, BUT NOT LIMITED TO, THE

Page 3: Unix Basics - UNAM

IMPLIED WARRANTIESOFMERCHANTABILITY AND FITNESSFORA PARTICULAR PURPOSE.THEENTIRE RISK OFUSEOFTHE OCIS WITH YOU. SHOULD THE OCPROVE FAULTY, INACCURATE,OROTHERWISEUNACCEPTABLE YOU ASSUMETHE COSTOFALL NECESSARY REPAIR OR CORRECTION.

5. IN NO EVENT UNLESSREQUIREDBY APPLICABLE LAW ORAGREEDTO IN WRITING WILL ANYCOPYRIGHTHOLDER,ORANY OTHER PARTY WHO MAY MIRRORAND/OR REDISTRIBUTETHE OCASPERMITTEDABOVE, BE LIABLE TO YOU FORDAMAGES,INCLUDING ANY GENERAL,SPECIAL,INCIDENTAL OR CONSEQUENTIALDAMAGESARISING OUT OFTHE USEORINABILITY TO USETHEOC,EVEN IF SUCHHOLDER OR OTHERPARTY HAS BEEN ADVISED OFTHE POSSIBILITYOFSUCHDAMAGES.

Additionally:

6. If youoffer trainingbaseduponthis OpenContent,youmustprominentlydisplaya noticestatingwhetheror not youarea NetizenCertifiedTrainingOrganisationon theOpenContentitself andon any materialadvertisingor publicisingyour training.

a) If youarea NetizenCertifiedTrainingOrganisation,you muststatethatyouarea NetizenCertifiedTrainingOrganisationanddisplaytheNetizenCertifiedTrainingOrganisationlogo.You mustalsoprovide a URL for moreinformation,namelyhttp://netizen.com.au/services/training/ncto/

b) If youarenota NetizenCertifiedTrainingOrganisation,youmuststatethatyou arenot aNetizenCertifiedTrainingOrganisation.You maynot usetheNetizenCertifiedTrainingOrganisationlogo.Youmustalsoprovide a URL formoreinformation,namelyhttp://netizen.com.au/services/training/ncto/

NetizenandtheN logoaretrademarksof NetizenPty Ltd. All rightsreserved.

Revision History

Revision 0.11999-09-29Revisedby: KRInitial versionRevision 0.91999-11-02Revisedby: KRBetateststageRevision 1.01999-11-10Revisedby: KRFirsteditionRevision 2.02000-02-02Revisedby: KRSecondeditionRevision 2.12000-06-14Revisedby: RLMinor revision

Page 4: Unix Basics - UNAM

Table of Contents1. Intr oduction.....................................................................................................................................7

About thiscourse........................................................................................................................7Courseoutline.............................................................................................................................7Assumedknowledge...................................................................................................................7Moduleobjectives.......................................................................................................................7Materials......................................................................................................................................8Platformandversiondetails........................................................................................................8Thecoursenotes..........................................................................................................................8

2. What is Unix? ................................................................................................................................10

In thischapter............................................................................................................................10Unix history...............................................................................................................................10Featuresof Unix........................................................................................................................10Flavoursof Unix........................................................................................................................11UnderstandingUnix ..................................................................................................................11Chaptersummary......................................................................................................................12

3. Logging in ......................................................................................................................................13

In thischapter............................................................................................................................13How to log in.............................................................................................................................13Whatwill you see?....................................................................................................................15Changingyourpassword...........................................................................................................16Loggingout...............................................................................................................................17Chaptersummary......................................................................................................................17

4. The shell.........................................................................................................................................19

In thischapter............................................................................................................................19Whatis a shell?.........................................................................................................................19Dif ferentshells..........................................................................................................................19Usingtheshell...........................................................................................................................20Chaptersummary......................................................................................................................31

5. Getting help...................................................................................................................................33

In thischapter............................................................................................................................33Manualpages............................................................................................................................33Otherdocumentation.................................................................................................................36Sysadmins:Careandfeeding....................................................................................................37Chaptersummary......................................................................................................................38

6. Filesand dir ectories......................................................................................................................39

In thissection............................................................................................................................39Everythingis a file ....................................................................................................................39Filenames..................................................................................................................................39Listing files................................................................................................................................39TheUnix system’sfile structure................................................................................................41

4

Page 5: Unix Basics - UNAM

Viewing files..............................................................................................................................41Copyingfiles.............................................................................................................................42Moving or renamingfiles..........................................................................................................43Deletingfiles.............................................................................................................................43Changingdirectories.................................................................................................................44Findingyour currentdirectory..................................................................................................44Creatinganddeletingdirectories..............................................................................................45Chaptersummary......................................................................................................................45

7. Editing ............................................................................................................................................47

In thischapter............................................................................................................................47Thevi editor..............................................................................................................................47Othereditors..............................................................................................................................51Chaptersummary......................................................................................................................54

8. Users,groupsand permissions....................................................................................................55

In thischapter............................................................................................................................55Users..........................................................................................................................................55Groups.......................................................................................................................................57Permissions...............................................................................................................................58Chaptersummary......................................................................................................................60

9. Processes........................................................................................................................................62

In thischapter............................................................................................................................62Whatis a process?.....................................................................................................................62Listing processes- thepscommand.........................................................................................62Killing processes.......................................................................................................................64Backgroundprocessesandjob control......................................................................................65Chaptersummary......................................................................................................................67

10.About Linux ................................................................................................................................68

Whatis Linux?..........................................................................................................................68Hardwarerequirements.............................................................................................................68GettingLinux ............................................................................................................................69Gettinghelp...............................................................................................................................70

11.Conclusion...................................................................................................................................71

Whatyou’ve learnt....................................................................................................................71Whereto now?..........................................................................................................................71Furtherreading..........................................................................................................................72

A. ASCII Pronunciation Guide .......................................................................................................73

5

Page 6: Unix Basics - UNAM

List of Tables3-1.Detailsrequiredto connectto theNetizentrainingserver..........................................................144-1.Commandhistory........................................................................................................................244-2.Defaultconfigurationfiles for variousshells...............................................................................264-3.Specialcharactersin promptsfor tcsh........................................................................................274-4.Specialcharactersin promptsfor bash.......................................................................................284-5.Someenvironmentvariables.......................................................................................................305-1.Navigatingmanpages.................................................................................................................335-2.Manualpagecategories...............................................................................................................346-1.Unix directoriesandtheircontents..............................................................................................416-2.Changingdirectories....................................................................................................................447-1. Inserting.......................................................................................................................................487-2.Movementcommands.................................................................................................................487-3.Simpletext editingcommands....................................................................................................497-4.Searchingandreplacing..............................................................................................................497-5.Yanking........................................................................................................................................507-6.Pasting.........................................................................................................................................507-7.Somefun andusefulcommands..................................................................................................507-8.Saving andquitting......................................................................................................................507-9.Layoutof editorcheatsheets.......................................................................................................518-1.Fieldsin /etc/passwd .................................................................................................................558-2.Abbreviationsfor groups.............................................................................................................598-3.Abbreviationsfor permissions.....................................................................................................609-1.BSD-stylecommandline switchesfor ps ...................................................................................63A-1. ASCII PronunciationGuide.......................................................................................................73

6

Page 7: Unix Basics - UNAM

Chapter 1. Intr oduction

About this cour seThisone-daytrainingmoduleprovidesabasicintroductionto theUnix operatingsystemfor thosewith no previousUnix experience.

Cour se outline

• Whatis Unix? (15 minutes)

• Loggingin (30 minutes)

• Theshell(60 minutes)

• Morning tea break

• Gettinghelp(15 minutes)

• Filesanddirectories(60minutes)

• Lunch break (60 minutes)

• Editing(60 minutes)

• Users,groupsandpermissions(60 minutes)

• Afternoon tea break

• Processes(60 minutes)

Assumed kno wledg eTo gainthemostfrom this course,youshouldalreadybefamiliar with personalcomputeroperatingenvironmentssuchasWindowsor MacOS.

Module objectives

• UnderstandwhatUnix is, themainfeaturesof Unix, anddifferentflavoursof Unix

• Know how to log in to a Unix account,changeyourpassword,andlog outagain

7

Page 8: Unix Basics - UNAM

Chapter 1. Introduction

• Understandthepurposeandfeaturesof theUnix shell,includingcommandhistory, filenameexpansion(globbing),aliases,etc.

• Know how to find helpof variouskindsona Unix system

• UnderstandUnix filesanddirectoriesandhow to manipulatethem,includingviewing, copying,moving anddeleting

• Know how to usethevi editor to manipulatetext files

• Understandtheconceptsof users,groupsandpermissionson a Unix system,andknow how to usecommandsto identify usersandgroups,andidentify andmanipulatepermissionsonfiles anddirectories

• UnderstandtheUnix conceptof processesandjob control,andknow how to kill processesandjobs,andhow to run processesor jobsin thebackground

MaterialsThematerialsfor this moduleinclude:

• Thesetrainingnotes

• A copyof thetextbook,Unix in a Nutshell(SystemV/Solaris,3rd edition)by Arnold Robbins

• Exercisesandotherfiles (on thetrainingserver andprovidedon floppydisk)

Platf orm and version detailsThismoduleis taughtusinga Unix or Unix-like operatingsystemsuchasLinux or FreeBSD.Mostof whatis learntwill work equallywell on othervariantsof Unix; your instructorwill inform youthroughoutthecourseof any areaswhich differ.

The cour se notesThesecoursenotescontainmaterialwhich will guideyouthroughthetopicslistedabove,aswell asappendicescontainingotherusefulinformation.

Thefollowing typographicalconventionsareusedin thesenotes:

Systemcommandsappearin this typeface

Literal text which you shouldtypein to thecommandline or editorappearsasmonospaced font.

Keystrokeswhich you shouldtypeappearlike this: ENTER. Combinationsof keysappearlike this:CTRL -D

8

Page 9: Unix Basics - UNAM

Chapter 1. Introduction

Program listings and other literal listings of what appears on the

screen appear in a monospaced font like this.

Partsof commandsor otherliteral text which shouldbereplacedby yourown specificvaluesappearslike this

Note: Notes and tips appear offset from the text like this.

Advanced: Notes which are marked "Advanced" are for those who are racing ahead or whoalready have some knowledge of the topic at hand. The information contained in these notes isnot essential to your understanding of the topic, but may be of interest to those who want toextend their knowledge.

Readme: Notes marked with "Readme" are pointers to more information which can be found inyour textbook or in online documentation such as manual pages or websites.

9

Page 10: Unix Basics - UNAM

Chapter 2. What is Unix?

In this chapter ...In thissectionwe will discussa little of thehistoryof theUnix operatingsystem,someof itsfeatures,andthedifferencesbetweendifferenttypes(or "flavours")of Unix. We’ll alsolook atsomewaysof thinking aboutUnix which mayhelpyouunderstandit better.

Unix histor yTheUnix operatingsystemwasdevelopedaround1970at Bell Labsby KenThompsonandDennisRitchie.It wasbasedon anearliersystemcalledMultics; thename"Unix" wasa punon "Multics"becauseUnix wasa cutdown versionof theearliersystem.

During the1970s,Unix wasre-implementedin theC programminglanguage,which allowedit to beeasilyportedbetweendifferenthardwareplatforms.This resultedin greaterpopularityfor theoperatingsystem,which beganto beusedwidely in universitiesandeventuallyin commercialorganisations.

As of thelate1990s,Unix runson everythingfrom smallPCsandembeddedprocessorsto hugemainframesandsupercomputers,andis usedfor tasksrangingfrom desktopcomputingandwordprocessingto scientificandfinancialnumber-crunching.

Features of Unix

Multi-user , multi-taskingUnix is amulti-user, multi-taskingoperatingsystem.

A multi-taskingoperatingsystemis onewhichcanrun multiple tasks(suchasprograms,applications,etc)at thesametime.This is usuallydoneby allocatinga few millisecondsto eachtaskin turn,soit appearsthatall thetasksarerunningsimultaneously.

A multi-useroperatingsystemis onewhich cansupportmultiple peopleusingthesamesystematthesametime.Eachusercanconnectto thesystemandruntheir own programswithout interferingwith otherusers.Unix systemscaneasilysupporthundredsof userssimultaneously.

Security

10

Page 11: Unix Basics - UNAM

Chapter 2. What is Unix?

If you have many usersusinga computersystemat thesametime, it is importantto ensurethattheycannotreadeachother’sfiles, interferewith eachother’sprograms,pretendto beanotheruser, orinterferewith theunderlyingoperatingsystem.This is referredto assystemsecurity.

Unix systemsprovide securityin severalways.Firstly, all usersmustidentify themselvesby loggingin with a usernameandpassword.Oncethey areloggedin, they mayonly reador write files,or runor stopprograms,for which they have permission.Theunderlyingoperatingsystemis alsoprotectedfrom interferenceby normalusers.

Network capabilitiesUnix systemsarecommonlyusedasserversfor networkservicessuchaselectronicmail, WorldWide Web,file andprintersharing,andmore.Unix serversprovide theseservicesthroughaninterfacecalled"sockets".

TheTCP/IPprotocol,on which theInternetruns,wasoriginally developedat theUniversityofCaliforniaatBerkeley for BSDUnix systems.

Flavour s of UnixUnix is nota singleoperatingsystem.Rather, it is a family of operatingsystemsbasedon a commonancestor, theoriginalBell LabsUnix.

Unix variants(or "flavours",asthey areoftencalled)areusuallyeither"SysV-ish" (thatis, mostlysimilar to SystemV Unix, which cameoutof theoriginalUnix at AT&T Bell Labs)or "BSD-like"(mostlysimilar to theBSDUnix variantsdevelopedlateratUC Berkeley).

Therearebothcommercialvariantsof Unix (suchasSun’sSolaris,IBM’ sAIX, Compaq’sTru64Unix (previouslyDigital Unix, previously OSF/1)andHewlett-Packard’sHP/UX) andnon-commercialvariantssuchasLinux andFreeBSD,NetBSDandOpenBSD.

This trainingmoduleattemptsto teachUnix in awaywhich is applicableto mostUnix variants.Whenthingsdiffer betweendifferentUnix flavours,your trainerwill point themoutandmaydemonstratethedifferenceto you.

Under standing Unix

As a langua geLearningUnix is like learninganotherlanguage.Like humanlanguages,Unix hasits ownvocabulary, grammarandsyntax,all of which areinitially difficult to grasp,but becomeeasierwith

11

Page 12: Unix Basics - UNAM

Chapter 2. What is Unix?

practice.

If you have ever learnta secondlanguage,you will know thatthefirst stagesarevery difficult, andthatit is only with perseverenceandpracticethatyou will becomefluentandeventuallystartto thinkor evendreamin thatlanguage.

As a toolUnix, like all computersystems,is a tool. However, it’ snot a hammeror a screwdriver -- Unix is aTriton workbench,with all kindsof attachmentsandspinningbladesandspecialisedattachmentslike routers(punvery muchintended).

If you’reusedto usinganordinaryhammer, or perhapsa differentkind of tool like a sewingmachine,youmight look ata Triton workbenchin bewilderment.Imaginetrying to find thebit on aTriton workbenchthat’susedfor bangingin nails,or theembroideryattachment!

Nevertheless,onceyou understandhow thetool worksandwhatits strengthsare,it canhelpyouwork muchmoreefficiently andprovideyou with ordersof magnitudemorepower thana hammerever could.

Chapter summar yIn thischapteryou have learnt:

• Unix is anoperatingsystemdevelopedaround1970atBell Labsby KenThompsonandDennisRitchie

• Unix is a multi-user, multi-taskingoperatingsystem

• Unix hasmany securityandnetworkingfeatures

• Unix comesin a varietyof different"flavours",bothcommercialandOpenSource.

• Thetwo mainflavoursof Unix are"SystemV" and"BSD"

• LearningUnix is like learninga new language,andrequirespatienceandpracticeto becomefluent

• Unix is avery powerful tool, moresimilar to a Triton workbenchthanahammer, andcanhelpyouwork veryefficiently onceyou learnhow to useall its attachments

12

Page 13: Unix Basics - UNAM

Chapter 3. Log ging in

In this chapter ...In thissection,youwill learnhow to log in to a Unix system,changeyour password,andlog outagain.

How to log inAlmost all Unix systemswill requireyou to "log in" beforeyou canusethem.Loggingin tells thesystemwho youare,providessecurityandmakesit possibleto have atruemulti-userenvironment.

To log in to aUnix systemyoueitherneedto besitting in front of thesystem’sconsole,or connecttothesystemvia a networkof somekind.

Thetool mostcommonlyusedto connectto anInternet-connectedUnix systemis calledtelnet andis availableonmostsystems,includingWindowsPCs.

To run telnet ona Windowsmachine,choose"Run" from theStartmenu,andtypetelnet into thedialogbox thatappears.You canalsotypetelnet hostname (wherehostname is thenameof theUnix systemyou’reconnectingto) to save having to usethemenusin thetelnet program.

Thisscreenshotshows theRundialogfrom which youcanrun thetelnet command.

Othertelnet/terminalemulationprogramsfor Windows include:

• TeraTerm

• QVTTerm/QVTNet

13

Page 14: Unix Basics - UNAM

Chapter 3. Logging in

Theseandothertelnetprogramsshouldbeavailablefrom any goodWindowssoftwaredownloadsiteon theWorld Wide Web,suchashttp://www.tucows.com/.

Advanced: Before the days of inexpensive PCs, people would use special terminals to connectto Unix systems. These were screens with keyboards but very little processor power (justenough to display things on the screen in text mode) which were sold by various hardwarevendors. These terminals would be connected by a serial line (like a modem cable) directly tothe Unix system.

Some of the most popular terminals were the VT terminals sold by DEC, including the VT-100,VT-220, and VT-320.

Modern telnet programs for PCs are also referred to as "terminal emulation" programs becausethey act like the old hardware terminals. In the setup menu of your telnet program, you should beable to choose which type of terminal to emulate. The most common is VT-100.

ExerciseUsetelnet to connectto Netizen’s trainingserver. Your trainerwill demonstratehow to do thisusingyour PC.You will needto fill in thefollowing detailsfor usethroughoutthiscourse:

Table3-1.Details required to connectto the Netizentraining server

Hostnameor IP address

Your username

Your password

You shouldseea screenlike this:

Trying 203.30.75.3...Connected to training.netizen.com.au.Escape character is ’^]’.

login:

You will have beengivena usernameandpassword.Typeyour usernamein whereit says"login",thenpressENTER. You shouldseethis:

login: train01password:

Typein your password,thenpressENTER. You will not seeanything on thescreen,for securityreasons- evena row of asteriskscouldindicatethenumberof charactersin your passwordto anobserver.

If you have typedin your usernameandpasswordcorrectly, you shouldseesomethinglike this:

Linux yt 2.2.12 #3 SMP Tue Sep 21 10:17:11 EST 1999 i586 unknown

14

Page 15: Unix Basics - UNAM

Chapter 3. Logging in

Last login: Mon Nov 8 22:22:53 from 123.4.5.6

You have new mail.%

This is theUnix commandline prompt.

If you arehaving troubleloggingin, checkthefollowing:

• Are you usingthecorrectmix of upperandlowercaseletters?Unix usernamesandpasswordsarecase-sensitive,soan"a" is not thesameasan"A".

• Sometimesthelogin screendoesnot understandthebackspacekey. If you aremakingmistakesandbackspacingover them,this maybetheproblem.JustpressENTER a coupleof timesuntilyouseeanew login prompt.

What will you see?

Message of the dayOn loggingin, youmaybepresentedwith a "messageof theday" (or MOTD) which is a messagefrom thesystemadministratorto theusers.Oftenthis messagewarnsof upcomingmaintenanceordowntimefor thesystem.Always readtheMOTD carefully.

Terminal typeSomesystemswill askyouto specifyyour terminaltype.If youareusingaterminalemulationprogram,this is mostlikely to be"vt100".

For tune cookieSomesystemswill print outa "fortunecookie"whenyou log in -- oftena shorthumourousquoteormessage.You cangeta fortunecookieany timeby usingthefortune command.

The promptFinally, youwill seea prompt.Thismaylook like any of thefollowing:

%$systemname:~>

user@systemname:~>

15

Page 16: Unix Basics - UNAM

Chapter 3. Logging in

... or any of a numberof differentthings(it’ sconfigurable-- we’ll learnhow later).

Thepromptis basicallythesystemtelling you it’ sreadyfor you to typein acommand.You cantypein any Unix commandat thecommandline, andpressENTER to run it.

Changing your pass wordTo changeyour password,youneedto usethepasswdcommand.Simply typepasswdinto thecommandline, andpressENTER.

% passwd

Changing password for train01Old password:

You needto typein your old passwordto provethatyou have theright to changethepassword.Thisprotectsyou a little in caseyou have wanderedaway from yourkeyboardandsomeoneelsetriestochangeyour passwordwithout yourpermission.

Next, typein a new passwordthenconfirmit by typing it in a secondtime:

New password:Re-enter new password:Password changed.

Notethatthepasswordsyoutypein never appearon thescreen.

Somesystemsrequireyouto usepasswordswhich aredifficult to guess,andmayrequirethatyourpassword:

• is longerthana givennumberof characters(usually5)

• containsnumbersand/ormixed-caseletters

• is nota commondictionaryword

• is not relatedto your username

• is not thesameastheoneyou previously used

Advanced: The passwords are stored in encrypted format in the /etc/passwd file, along withother information about the user.

The type of encryption used is “one-way” which means that the password stored in /etc/passwd

cannot be decrypted. Instead, the password typed in by the user when logging in is encrypted inthe same way, and the two encrypted passwords are compared.

A common way of finding out someone’s password is called a “dictionary attack”, whereby all thewords in a dictionary are encrypted and compared to the encrypted passwords in /etc/passwd.This is why many systems require that your password consist of mixed upper and lower caseletters and numbers, and not be a common dictionary word.

16

Page 17: Unix Basics - UNAM

Chapter 3. Logging in

Hints for thinking up a good pass word

• Takea wordandsubstitutecertainlettersfor numbersor othersymbols.For instance,changeall"i" charactersto thenumber1 or the| (pipe)symbol,or changeall instancesof theletter"s" todollarsigns.

• Takea memorablephrase,a line of a song,or a famousquotation,andusethefirst letterof eachwordasyourpassword.For instance,"Now is thewinterof our discontent"couldbecome"Nitwood", or even"N1tw00d" (usingthenumbersoneandzeroinsteadof normalletters)

What to do if you forget your pass wordIf you forgetyourpassword,you will needto contactyour techicalsupportstaff or systemadministratorto getit changed.Notethatthey won’t beableto tell you whatit currentlyis -- eventhesystemadministratorcan’t find thatout.You will have to begivena new password,which youcanthenchangeto somethingmorememorableif necessary.

Exercise

1. Changeyour passwordusingthepasswdcommand

Log ging outTo log outof thesystem,simply type logout andpressENTER.

Somesystemsalsoallow youto logoutby typing exit or usingCTRL -D.

Note: Some systems are set up to automatically log you out after some period of inactivity.

Exercise

1. Try loggingoutandin againusingeitherCTRL -D or the logout command.

Chapter summar y

17

Page 18: Unix Basics - UNAM

Chapter 3. Logging in

In thischapteryou have learnt:

• how to log in to a Unix system

• how to changeyour passwordusingthepasswdcommand

• sometechniquesfor creatingsecurepasswords

• how to log outof a Unix systemusingeitherthe logout commandor othermeans.

18

Page 19: Unix Basics - UNAM

Chapter 4. The shell

In this chapter ...In thissectionyou will learnabouttheUnix shell,which processescommandstypedby theuser.

What is a shell?TheUnix operatingsystemitself doesnot handlecommandstypedin by theuser. Instead,thereis aprogramcalledashellwhich interpretsusercommandsandpassesmessagesto theunderlyingoperatingsystem.

Whatyou seewhenyoufirst log in to a Unix systemis theshell.Usuallytherewill bea promptwhich lookssomethinglike this:

train01@vitaly:~>

Thepromptvariesconsiderablydependingon theshellusedandthespecificsetup.Modernsetupsusuallyshow theusername,thenameof theUnix system,andthedirectorytheuseris currentlyin.Oldersystemsmaynothave configuredtheshell to do this,andmaysimplyshow a percentsign(%)or a dollarsign($ dependingon theshellused.In theexamplesgivenin thesenotes,we’ll usuallyuse% to indicatethecommandline prompt,like this:

% passwd

This is commonusage,andyou’ll oftenseeit in otherbooksanddocumentation.

Readme: Chapter 3 of the textbook, "The Unix Shell: An Overview" introduces the shell in moredetail. It begins on page 201.

Diff erent shellsThereareseveraldifferentshellsavailableon mostUnix systems.Thetwo mostbasiconesarecalledtheBourneshell(namedfor its inventor)andtheC shell(which is botha punon "seashell"andanindicationthatit hassomesimilarity to theC programminglanguage).Theprogramswhichruntheseshellsarecalledsh andcshrespectively.

Two moremodernshellsaretheBourneAgain shell(yes,anotherpun)which is calledbash, andtcsh which is anenhancedversionof csh.

19

Page 20: Unix Basics - UNAM

Chapter 4. The shell

Note: The T in tcsh stands for TENEX, the name of a 1970s era operating system. You can readthe story about it in the tcsh manual page by typing man tcsh .

Lastly, therearea numberof lesscommonshellssuchas:

• ksh

• zsh

Readme: The Bourne and Korn shells are described in chapter 4 of the textbook, beginning onpage 207. The C shell is described in chapter 5, beginning on page 260.

In this trainingmodule,we will primarily usetcshandalsotakea brief look atbash. Thenoteswillusuallydescribetechniquesto usein bothshells,but you canmostlyignorethebash instructionsfornow, andjustusethemasa referencein thefuture.

Advanced: Some systems will be set up to allow you to change your shell using the chshcommand. Simply type chsh at the command line and follow the prompts. You will have to typein your password, and specify the full path to the shell you wish to use.

For more information about the chsh command, type man chsh .

Using the shell

Simple commandsThemostsimplecommandin Unix is a singleword,which is thenameof a programto run.

% passwd

% fortune

To run a simplecommand,simply typethecommand’s nameandpressENTER. Notethatprogramnamesin Unix areusuallyall lowercasecharacters,andarecasesensitive-- if youuseuppercasecharacters,you will getanerrormessage.

Note: Unix command names tend to be very short, often only a couple of letters. The originaldevelopers of Unix either suffered from very bad RSI or were too lazy to type long commands,and thus tended to abbreviate every command to as few characters as possible. Hence"password" became pass wd , "copy" became cp , "make directory" became mkdir , and so on.

And if you think that’s confusing, just wait til you hear about some of the commands with reallyobscure names -- for instance, there’s an email notification utility called biff that’s named afterthe labrador retreiver at UC Berkeley that used to bark when the postman delivered mail.

20

Page 21: Unix Basics - UNAM

Chapter 4. The shell

Somecommandstake"arguments"or "parameters".Theseareextra partswhich comeafterthecommand’s nameandvary thebehaviour of thecommand.

For instance,to print outa shortmessageto thescreen:

% echo Hello

In theexampleabove,echois thecommand,andtheword Hello is theargument.

To find a "long" fortunecookiemessage:

% fortune -l

In theexampleabove, the-l (pronounced"dash-ell")is theargument.

To find all fortunecookiemessagescontainingtheword "Winston"(for instance,thosewhich arequotesmadeby WinstonChurchill):

% fortune -m Winston

In thiscase,the-m Winston area commandline switchandthevalueassociatedwith thatswitchwhich means"find quoteswhich matchtheword ’Winston’".

An argumentor parameterwhich startswith a hyphenis oftenreferredto asa "commandlineswitch" or simplya "switch". You canthink of thecommandashaving adashboardor panelwith arow of switcheson it, andyou flick down any switchesyouwantto affect how theprogramruns.Someswitchestakevalues(asin thecaseof -m Winston), while othersaresimplyon or off (asin theearlierexampleof fortune -l for a long fortunecookie).

Note: The dash or hyphen used on Unix command line switches is similar in purpose to theslash (/) used under MS-DOS. Unix can’t use a slash because it uses that character as adirectory separator, where MS-DOS uses a backslash (\).

Somecommandstakea filenameasanargument.For instance,thecat canbeusedto print a text fileto thescreen:

% cat myfile.txt

This is my file.It contains several lines of text.Here is some more text from my file.%

Readme: Common Unix commands are described in Chapter 2 of the textbook, starting on page11.

Exercise

1. Try someof thecommandsgivenabove by typing themat theshellprompt.

21

Page 22: Unix Basics - UNAM

Chapter 4. The shell

• fortune

• fortune -l

• fortune -m Winston

• cat myfile.txt

Filename wildcar dsSometimeswhenusingacommandwhichtakesa filenamefor anargument,wewantit to useseveralfiles atonce.Sometimeswe canspecifyall thefilenamesoneaftertheother:

% cat myfile.txt otherfile.txtThis is my file.

It contains several lines of text.Here is some more text from my file.This is my other file.It contains different text to myfile.txt%

However, if we wantto acton severalfiles atonceandthey all have similar names,we canuse"wildcards"to specifythegroupof files wewant.Thecorrectnamefor wildcardsunderUnix isglobs, andtheprocessby which theshellexpandsglobsto matchfilenamesis calledglobbing.

Themostcommonlyusedglobcharacteris theasterisk,or star. It represents"anything", or morespecifically, zeroor moreunknown charactersin a filename.

To print out all files startingwith theletterA:

% cat a*

To print out all text files:

% cat *.txt

Thereareotherglobcharacterswith othermeanings,too.Thecharacter?, for instance,indicatesanysinglecharacter.

To matchfiles whosenamesareasingleletterfollowedby .txt:

% cat ?.txt

Squarebrackets([ and] canbeusedto specifya groupof characters,any oneof which maybematched.For instance,b[aeiou]g wouldmatchbag, beg, big, bog, andbug.

Readme: Globbing is discussed in the tcsh manual page under "Filename substitution" and inthe bash manual page under "Pathname expansion".

22

Page 23: Unix Basics - UNAM

Chapter 4. The shell

Advanced: The shell performs expansion on its arguments, which means that it expands anywildcards out into a list of matching files, substitutes in any variables specified on the commandline, and so on. This expanded command line is then passed to the program itself. It is importantto note that programs under Unix do not ordinarily do their own expansion of arguments. This iscontrary to the behaviour of MS-DOS, where all expansion is handled by the programs.

Exercise

Practiceusingcat to print out

• all fileswith theextension.txt

• all fileswhosenamesstartwith "a"

Filename completionMany modernshells,suchasbashandtcsh provide filenamecompletion.Thiscansave youtypingout longfile names.For instance,if you hadtyped:

% cat myf

in tcsh, you couldpressTAB to have it automaticallycompletethefilenamefor you:

% cat myfile.txt

If theshellcannotcompletethefilename,it will completeasmuchasit is ableto, andusuallymakea beepingsound.

Exercise

• Practiceusingtheshell’sfilenameexpansion

Command histor yMost shellsprovidea commandhistory. This is a facility which rememberscommandsyoupreviously typedandallowsyou to repeatthemeasily.

Modernshellssuchasbashandtcsh allow you to usetheUP andDOWN arrow keys to scrollforwardsandbackwardsin yourcommandhistory. Simply usethearrow keys to move upor down tothecommandyou want,optionallyedit it if youwantto makeany changes,thenpressENTER torun it again.

23

Page 24: Unix Basics - UNAM

Chapter 4. The shell

All shells,includingoldershellssuchassh andcshallow youto accessthecommandhistoryusingspecialshellcommands:

Table4-1.Commandhistory

Command Meaning

history list commandhistory

!! repeatpreviouscommand

!n repeatcommandn from history list

!string repeatmostrecentcommandstartingwithstring

!$ lastargumentof previouscommand

^old^new repeatlastcommand,substitutingold withnew

Exercise

• Practiceusingthehistorycommandslistedabove.

Redirection and pipesSometimeswe wantto save theoutputof a commandto a file, suchaswhenwe ranfortune -mWinston andsaw a long list of quotesby WinstonChurchill whichflew by too quickly to read.

Othertimes,we wanttheoutputof onecommandto becometheinput to anothercommand-- forinstance,we couldtaketheoutputof cat andusethesort commandon it to sorttheoutput.

Themechanismsusedto achieve this underUnix arecalled"redirection"and"pipes".

Standar d input, output and error

Programstypically have input (thedatawhich is givento theprogram)andoutput(thedataproducedby theprogram).Programsmayalsoproduceerrormessages.

Undernormalcircumstances,theinput to aprogramunderUnix is theusertyping thingsat theirkeyboard,andtheoutputis to theterminal.Thesearecalled"standardinput" and"standardoutput"respectively, andareoftenabbreviatedto "STDIN" and"STDOUT". Errormessagesareusuallyalsooutputto theterminal.This is referredto as"standarderror"or "STDERR"for short.

24

Page 25: Unix Basics - UNAM

Chapter 4. The shell

Thisdiagramshowstheflow of datainto aprogramthroughstandardinput,outvia standardoutput,with errorscomingout throughstandarderror.

However, standardinputdoesn’t necessarilyhave to bethekeyboard,andstandardoutputanderrorsdon’t necessarilyhave to betheterminal.

We cancausea programto takeits input from a file asif thecontentsof thatfile werebeingtypedatthekeyboard.We canalsosendthestandardoutputof a programto a file soit appearsin thatfileexactly asit wouldhave on theterminal.This is calledredirection.

If we taketheoutputof onecommandandfeedit directly into theinput of another, that’scalleda"pipe". You canimaginetheprogramsasa seriesof machinesconnectedtogetherby pipes;you pourtheinput in atoneendthenit flows througheachmachinein turnvia thepipes,andeventuallycomesout theotherend.

Using redirection to output to files

To redirecttheoutputof a command,we usethegreater-thansymbol,which lookslike anarrowpointingoutof theprogramandinto thefile:

% fortune -m Winston > quotes.txt

We canappendto anexisting file usinga doublegreater-thansign.Thefollowing examplesearchesthefortunecookiesfor quotesby OscarWilde andaddsthemto thequotesfile wecreatedearlier:

% fortune -m Wilde���

quotes.txt

25

Page 26: Unix Basics - UNAM

Chapter 4. The shell

Exercise

• Runthefirst commandshown above to outputa list of quotesby WinstonChurchill to a file calledquotes.txt

• Usethesecondcommandshown above to appendsomeOscarWilde quotesto your quotes.txtfile.

Using redirection for input, and using pipes to filter output

We canuseourquotesfile asinput to anotherprogram,suchassort, by usingtheless-thansymbol:

% sort � quotes.txt

We cancombinethem,sothatthesortedoutputis sentto anotherfile:

% sort � quotes.txt > sorted.txt

However, oftenwe will combinemany stepsinto oneusinga pipe.Pipesusethevertical-barcharacterwhich is usuallyon thesamekey asthebackslash.Thefollowing commandfindsWinstonChurchill quotesin thefortunecookiedatabase,pipestheoutputthroughthesort, thenredirectstheoutputto a file.

% fortune -m Winston | sort > sorted.txt

We will beusingredirectionandpiping muchmorewidely in theUnix Tools trainingmodule,whichfollowstoday’straining.

Configuring the shellYou canconfigureyourshell to look or behave differentlydependingon yourneedsandpreferences.Think of it asbeingsimilar to theWindowscontrolpanel,whereyou canchoosevarioussettingstocustomisethedesktopandprogramsto your personaltastes.

UnderUnix, configurationcommandscanbetypeddirectly into thecommandline. However, typingthemin every timeyou login to a Unix systemwouldnotbeveryuseful.Moreusually, they’reallkeptin a file which is automaticallyreadby theshellwhenit startsup (thatis, whenyou log in).

Eachshellhasa differentfile thatit keepsits configurationcommandsin:

Table4-2.Default configuration files for various shells

Shell Configuration file

sh .profile

26

Page 27: Unix Basics - UNAM

Chapter 4. The shell

Shell Configuration file

csh .cshrc

bash .bashrc

tcsh .tcshrc

Thesefilesareusuallyfoundin your homedirectory. Theleadingdoton their namesmeansthattheyarehiddenfiles.

For now, we’ll beenteringconfigurationcommandsdirectly into thecommandline. Later, afterwe’ve learnthow to usea text editor, we’ll createa.tcshrc file sothatour configurationcommandswill berunwhenever we log in to thesystem.

Setting the prompt

Most shellsallow you to customiseyour prompt.Often,thepromptwill becustomisedto show whatsystemyouareloggedin to, whatusernameyou areusing,or whatdirectoryyouarein.

Detailsof changingyourpromptaregivenbelow for bashandtcsh. To changeyour promptinanothershell,readthemanualpagefor thatshell.

Setting the prompt using tcsh

Undertcsh thepromptis setby settingtheprompt variable:

training:~> set prompt="What is your command? "What is your command?

Thefollowing charactersareasampleof thosewhich canbeusedto putspecialinformationinto theprompt.

Table4-3.Specialcharactersin prompts for tcsh

Character s Meaning

%/ Thecurrentworkingdirectory

%M Thefull hostname(egtraining.netizen.com.au)

%m Thefirst partof thehostname(eg training)

%T Timeof dayin 24 hourformat

%n Username

Herearesomeexamples:

% set prompt = "What is your command? "What is your command? set prompt = "%m: "training: set prompt = "%n@%m: "train01@training: set prompt = "%n@%m:%/> "

27

Page 28: Unix Basics - UNAM

Chapter 4. The shell

train01@training:/home/train01>

Readme: More information about special characters in prompts for tcsh can be found in thetcsh manpage.

Setting the prompt using bash

Underbash thepromptis setby changingthevalueof thePS1 variable:

bash-2.01$ PS1="What? "What?

Thefollowing tableshowscharacterswhichcanbeusedin a promptandwhichwill besubstitutedwith a pieceof usefulinformation.

Table4-4.Specialcharactersin prompts for bash

Character s Meaning

\w Thecurrentworkingdirectory

\H Thehostname(eg training.netizen.com.au)

\h Thefirst partof thehostname(eg training

\t Currenttime in 24-hourformat

\u Your username

Readme: More information about special characters in prompts for bash can be found in thebash manpage, in the section labelled "PROMPTING".

Exercise

1. Changeyour promptfrom thecommandline. Experimentwith differentpromptsandfind oneyou like.

2. A goodoneto try is setprompt="%m:%/> "

Aliases

Most shellsprovidethefacility of setting"aliases",which areusuallyabbreviationsfor longercommands.For instance,if youwanteda shorterway to geta fortunecookie,you couldmakeanaliassothatyouonly hadto typef insteadof thefull command.

28

Page 29: Unix Basics - UNAM

Chapter 4. The shell

Thesectionsbelow look at how to createaliasesin bashandtcsh. If you areusinga differentshell,you will needto readtherelevantmanualpageto find outhow to setaliasesin thatshell.

Aliasesin tcsh andbasharesetusingthealiascommandandunsetusingtheunaliascommand.

Thealiascommandcanbeusedto list thealiasesyou have set,or maytakestwo arguments-- thealiasto beset,andwhatto expandit to -- to createanalias.Underbash, you will needto put anequalssign(=) betweenthetwo argumentsandenclosethefull versionof thecommandyou wantexecutedin quotemarks,if it is morethanoneword long.

Hereis a tcsh example:

training:~> alias winnie fortune -m Winstontraining:~> winnieMen occasionally stumble over the truth, but most of them pick themselves

up and hurry off as if nothing had happened.-- Winston Churchill

training:~> unalias winnietraining:~> winniewinnie: Command not found.

training:~>

Hereis theequivalentbashexample:

bash-2.01$ alias winnie="fortune -m Winston"bash-2.01$ winnieMen occasionally stumble over the truth, but most of them pick themselvesup and hurry off as if nothing had happened.

-- Winston Churchill

bash-2.01$ unalias winniebash-2.01$ winniebash: winnie: command not found

Readme: More information about aliases in tcsh can be found in the tcsh man page, under"Alias substitution". More information about aliases in bash can be found in the bash man page,under "ALIASES".

Exercise

1. Createanaliasfor thefortune command.

2. Usethealiaswith no argumentsto list your aliases

3. Deletethataliasusingtheunaliascommand.

Envir onment variables

29

Page 30: Unix Basics - UNAM

Chapter 4. The shell

Environmentvariablesareessentiallysettingswhich tell theshellhow to behave in certaincircumstances.For instance,you cansettheEDITOR variableto tell theshellwhatyour favouriteeditoris, andit will look at thatvalueandbringuptheappropriateeditorby defaultin somesitations.

Someof theenvironmentvariablesyou cansetinclude:

Table4-5.Someenvir onment variables

Variable name Meaning

EDITOR Your favouritetext editor

PATH Wheretheshellshouldlook for programsto run

HOME Thelocationof yourhomedirectory

http_proxy TheURL of your webproxyserver

NNTPSERVER Thehostnameof your Usenetnews server

MAIL Thelocationof youremail"inbox"

Therearemany otherenvironmentvariableswhich youcanset.Often,themanualpagesfor aprogramwill have a sectionat thebottomentitled"ENVIRONMENT VARIABLES" which will listenvironmentvariableswhosesettingsaffect thefunctioningof theprogramin question.

Envir onment variables in csh and tcsh

To setenvironmentvariablesin cshor tcsh, usethesetenv command.

% setenv NNTPSERVER news.netizen.com.au% setenv EDITOR /bin/vi

You canview environmentvariablesettingsby usingthesetenv commandwith no arguments.

% setenv

GROUP=fredHOME=/home/fredPATH=/bin:/usr/bin:/usr/local/binUSER=fred

Envir onment variables in sh and bash

To setenvironmentvariablesin sh or bash, youfirst setthevalue,thenensureit will beexportedtoany programssubsequentlyrun by usingtheexport command.

% EDITOR="/bin/vi"% export EDITOR

You canview environmentvariablesettingsby usingthesetcommandwith no arguments.

% set

GROUP=fred

30

Page 31: Unix Basics - UNAM

Chapter 4. The shell

HOME=/home/fred

PATH=/bin:/usr/bin:/usr/local/binUSER=fred

Sample configuration files

Herearesomesampleconfigurationfiles for tcsh andbash. Later, afterwe’ve learnthow to useatext editorunderUnix, we’ll becreatingour own configurationfiles to customisetheshellenvironmentto our own tastes.For now, thesearejusthereasareferencefor lateruse.

Notethatlinesbeginningwith ahashsign(#) arecomments.

Sample .tcshrc configuration file

# set the prompt

set prompt="%m:%/> "

# set some aliasesalias f fortunealias rm rm -ialias dir ls -al

# set our favourite editorsetenv EDITOR /usr/bin/vim

# set our web proxysetenv http_proxy http://proxy.netizen.com.au:8080/

Readme: A default .cshrc file is given in the textbook on page 269.

Sample .bashrc configuration file

# set our promptPS1="\h:\w> "export PS1

# some aliasesalias f fortunealias rm rm -ialias dir ls -al

# set some miscellaneous environment variablesMAIL=/var/spool/mail/skudEDITOR=/usr/bin/vimPAGER=/usr/bin/lesshttp_proxy=http://proxy.netizen.com.au:8080/export MAIL EDITOR PAGER http_proxy

31

Page 32: Unix Basics - UNAM

Chapter 4. The shell

Chapter summar y

• In Unix, theshellis whatinterpretswhatyou typeandturnsit into commandsfor thesystemto run

• Therearedifferentshellsthatyoucanuse,dependingon yourpersonaltasteandwhat’s installedon thesystem

• Theseincludesh, csh, bash, tcsh andothers

• tcsh is theshellprimarily usedfor examplesthroughoutthis trainingmodule

• Simplecommandsarerun by typing thenameof thecommandandpressingENTER

• Morecomplex commandscanberun by addingargumentsto thecommandline

• Argumentswhich startwith adashor hyphen(-) arereferredto asswitches

• Groupsof files canbeselectedby usingwildcards(known asglobs underUnix)

• Mostmodernshellswill automaticallycompletefilenamesif youpressTAB

• Mostmodernshellsallow you to accessandedit earliercommandsusingarrow keys; therearealsospecialcommandsfor manipulatingearliercommands

• Redirectionandpipescanbeusedto providedifferentinputandoutputto programs

• Theshellcanbeconfiguredin variouswaysto suit your preferences

• You cansetthepromptto whatever you want

• You cancreatealiasesto providecommandshortcuts

• You cansetenvironmentvariablesto influencethebehaviour of someprograms

• You canput all your configurationcommandsinto afile whichwill bereadwhentheshellstarts

32

Page 33: Unix Basics - UNAM

Chapter 5. Getting help

In this chapter ...In thissectionyou will learnaboutthethreemainwaysto find helpwhenusinga Unix system:manualpages,otherdocumentation,andyour systemadministrator.

Manual pagesAlmost all Unix programscomewith manualpages.Theseareterse,technicalexplanationsof whattheprogramdoes.

To reada manualpagefor any commandtypemancommandname (substitutingtheappropriatecommandname,of course).

For instance:

% man passwd

Thiswill giveyou informationaboutthepasswdcommandwhich weusedearlier. Herearethefirstfew linesof thepasswdmanpage:

PASSWD(1) PASSWD(1)

NAMEpasswd - change user password

SYNOPSISpasswd [-f|-s] [name]passwd [-g] [-r|R] grouppasswd [-x max] [-n min] [-w warn] [-i inact] namepasswd {-l|-u|-d|-S} name

DESCRIPTIONpasswd changes passwords for user and group accounts. Anormal user may only change the password for their ownaccount, the super user may change the password for anyaccount. The administrator of a group may change the

password for the group. passwd also changes accountinformation, such as the full name of the user, theirlogin shell, or password expiry dates and intervals.

Themanpagesarepresentedto you usinga pagerprogramwhich allowsyou to view thetext ascreenfulata time.Onmostmodernsystems,thispageris a programcalledless. You canscrollthroughthemanpagesasfollows:

33

Page 34: Unix Basics - UNAM

Chapter 5. Getting help

Table5-1.Navigating man pages

Movement Keystr oke

Down a page SPACE

Up a page b

Down oneline j or ENTER

Up oneline k

Searchfor a string /string

Quit q

Note: The above table assumes that your system uses the less program as its pager. Someolder systems use more which does not allow you to go back in the file, only forward. An evenmore antiquated pager called pg is very occasionally seen; if your system uses this, be veryafraid.

Finding the right man pageIf you have someideawhatyouwantto do,but aren’t sureof theexactcommandname,youcangeta list of likely manualpagesby usingtheaproposor man -k commands.Thesecommandsareroughlyequivalent;bothsearchfor keywordsin thesingle-linedescriptionof utilities andprogramsasgivenin theirmanualpages.

% man -k "card game"canfield (6) - the solitaire card game canfieldcribbage (6) - the card game cribbage

% apropos "card game"canfield (6) - the solitaire card game canfieldcribbage (6) - the card game cribbage

Categories for man pagesThemanualpagesonany Unix systemareseparatedinto categories.Thesecategoriesvaryslightlybetweensystems,but typically they are:

Table5-2.Manual pagecategories

Category number Category contents

1 Executableprogramsor shellcommands

2 Systemcalls(functionsprovidedby thekernel)

3 Library calls(functionswithin systemlibraries)

34

Page 35: Unix Basics - UNAM

Chapter 5. Getting help

Category number Category contents

4 Specialfiles (usuallyfoundin /dev)

5 File formatsandconventionseg /etc/passwd

6 Games

7 Macropackagesandconventionseg man(7),groff(7).

8 Systemadministrationcommands(usuallyonlyfor root)

Sometimesit will happenthattherearemultiple manualpageswith thesamename,but in differentsectionsof themanual.For instance,thereis a manualpagefor thepasswdcommandandalsoforthefile with thesamenamewhich is foundin /etc/passwd.

You candistinguishbetweenthesemanualpagesby typingman n command wheren is thesection/category number.

% man 5 passwd

PASSWD(5) PASSWD(5)

NAMEpasswd - The password file

DESCRIPTIONpasswd contains various pieces of information for eachuser account. Included is

Login name

Optional encrypted password

...

As youcansee,this is a differentmanualpageto theoneyou wouldseeif you just typedmanpasswd. Thesystemwill, by default,choosethelowest-numberedmanualsectionfirst, sothemanpasswdwoulddefaultto man 1 passwd(thepasswdcommand)over thefile /etc/passwd which isdocumentedin section5, andwouldbeviewedby typing man 5 passwd.

Note: Some systems require you to use man -s section-number command instead of justman section-number command.

How manual pages are writtenMost manualpagesstartout with a nameandbrief descriptionof thecommandin question,thenavery brief (andratherarcane)summaryof all availablecommandline options.

35

Page 36: Unix Basics - UNAM

Chapter 5. Getting help

Thebulk of mostmanualpagesis madeup of a descriptionof all thecommandline optionsto thecommandandwhateachonedoes.Typically therewill bea few linesof discussionfor everypossibleoption.Someexamplesof usagemayalsobegiven.

At thebottomof themanualpage,you will oftenfind sectionsmarked"BUGS" (known problemswith thecommand),"FILES" (fileswhich arerelatedto thecommand),"ENVIRONMENTVARIABLES" which affect thebehaviour of thecommand,"SEEALSO" which lists othermanualpageswhich arerelated,and"AUTHOR" which namestheauthorof theprogramandoftenprovidesa contactemailaddress.

Exercise

1. Takea look at someof themanualpagesfor programswe’ve lookedat sofar:

• fortune

• passwd

• cat

• tcsh

Other documentationSometimes(in fact,often)themanpagesaretoo terseandtechnicalfor yourneeds.Man pagesfocuson thesyntaxof commandsratherthanon "How do I..." or "Why shouldI..." To find out thatkind ofinformation,you will needto readotherdocumentation.

Therearethreemainplacesto find otherdocumentation:

• Thedocumentationdirectory

• TheWorld WideWeb

• Books

The documentation director yOnmostsystems,thedirectory/usr/doc or /usr/local/doc will containadditionaldocumentationfor installedsoftware,includingFAQs(FrequentlyAskedQuestionfiles),examplesof use,etc.

WWW documentation

36

Page 37: Unix Basics - UNAM

Chapter 5. Getting help

A greatdealof documentationis availableon theWorld Wide Webor elsewhereon theInternet.Many FAQsandtutorialsareavailable,including:

• "Unixhelp for Users"from theUniversityof Edinburgh,athttp://unixhelp.ed.ac.uk/

• NormMatloff ’s"Unix Tutorial Center"at theUniversityof CaliforniaatDavis, athttp://heather.cs.ucdavis .edu/~matloff/unix.html(http://heather.cs.ucdavis.edu/~matloff/unix.html)

• "A BasicUnix Tutorial" from IdahoStateUniversity, at http://www.isu.edu/departments/comcom/unix/workshop/unixindex.html(http://www.isu.edu/departments/comcom/unix/workshop/unixindex.html)

Exercise

1. Usea searchengineor webdirectoryto searchfor Unix tutorialsor otherdocumentation.Somesearchenginesinclude:

• Googleathttp://www.google.com/

• Altavistaathttp://www.altavista.com/

• Yahooat http://www.yahoo.com/

2. Shareyourfindingswith theclass

BooksThereareliterally hundredsof booksavailableaboutUnix andUnix applications,rangingfrom verysimplistic“Dummies” booksto highly technicaltomes.Takethetime to visit a goodbookshopandbrowsetheir shelves.

Sysadmins: Care and feedingIf neithermanpagesnor otheronlinedocumentationnor bookshave helpedyou solveyour problem,you mayneedto consultyour systemadministratoror othertechnicalsupportstaff. Herearesomehintsyou will find useful:

• ReadthemanualsFIRST, andexplain whereyou have alreadylooked.Example:“I’m trying touseX to do Y, but themanpagesfor X don’t seemto containtheinformationI need.”

• Explainyour eventualgoal,not just thetoolsyou arehaving troublewith. Example:“I’m trying tosave my emailto differentfolder eachmonth”, ratherthan“Do crontabshave anoptionfor setting

37

Page 38: Unix Basics - UNAM

Chapter 5. Getting help

themonth”.Thelatterexamplewill causeconfusion,sinceyoursysadminor supportpersonwon’tunderstandwhatyou’reactuallytrying to do.

• If youaregettinganerrormessage,copyit out in full. Example:"It saidPermissionDeniedwhenI tried to cat/dev/audio"is muchmoreusefulthan"It gave meanerrormessage".Theworstpossibleerrorreportis "it doesn’t work". If yousaythis to yoursystemadministrator, donotexpectany kind of helpful response.

• A sysadmin’smainjob is keepingthesystemsrunning,nothelpingend-users.Becauseof this,they areoftengrumpywhenyou askthemfor help,andmayrequireappeasement.SystemAdministratorsoftenappreciatedonationsof chocolate,pizza,beer, Jolt cola,etc.Beniceto yoursysadmins,andthey will beniceto you.

Chapter summar y

• Mostdocumentationandhelpon Unix systemscanbefoundin theonlinemanuals

• Themanualsareaccessedusingtheman command

• Theaproposcommandcanbeusedto find which manualpagesbestmatchyour needs

• Additionaldocumentationcanoftenbefoundin the/usr/doc or /usr/local/doc directorieson aUnix system

• Therearemany Unix-relatedresourceson theWorld Wide Web

• Mostbookshopswill have severalbookson Unix which maybeof useto you

• As a lastresort,youcanconsultyour systemadministrator. Bribesof pizza,caffeineor alcoholareoftena goodway to gaintheirassistance.

38

Page 39: Unix Basics - UNAM

Chapter 6. Files and directories

In this section...In thissectionwe look at theUnix file systemandlearnto find ourway aroundby changingdirectories,listing files,andlookingat thecontentsof files.

Everything is a fileUnderUnix, almosteverythingis a file andcanbeviewedandmanipulatedvia thefile system.Hardwaredevices,directories,email,logs,configurationfor programs- all aresimplyfiles whichcanbetreatedin exactly thesameway.

FilenamesFilenamesunderUnix maycontainany characterotherthan/ ("slash")which is reservedasthedirectoryseparator. Typically, filenamesonly usealphabeticandnumericcharacters,underscores,hyphensanddots,asothercharacters(suchasdollarsigns,spaces,etc)have aspecialmeaningto theshellandcanbeannoyingto work with.

Unix supportslongfilenames,usuallyup to 255charactersin length(thisvariesfrom systemtosystem).

You do not needto giveUnix filesanextensionlike .doc or .exe - theoperatingsystemcanfigureout whattypea file is by othermeans.Nevertheless,it is oftenusefulto usea suitableextensiontoremindyourselfwhatfilesarewhat,andto makeit easierto manipulategroupsof files (for exampleall C programs,whichusuallyhave theextension.c).

Filenameswhich begin with a dotarehiddenanddo notappearin directorylistingsunlessyouspecificallyaskfor them.

Listing filesThe ls commandis usedto list files in any directory. This is analogousto DOS’sDIR command.

changes.sgml help.sgml shell.sgml

editing.sgml intro.sgml unixbasics.sgmlfilesanddirectories.sgml loggingin.sgml usersandgroups.sgmlfurtherreading.sgml processes.sgml whatisunix.sgml

39

Page 40: Unix Basics - UNAM

Chapter 6. Files and directories

Long formatTo geta long-formatlisting, showing permissions,ownership,file size,andotherinformation,usels-l.

-rw-r--r-- 1 skud skud 391 Nov 2 21:12 changes.sgml-r--r--r-- 1 skud skud 13938 Nov 9 11:09 editing.sgml-rw-r--r-- 1 skud skud 9238 Nov 9 11:42 filesanddirectories.sgml

-r--r--r-- 1 skud skud 973 Oct 20 00:45 furtherreading.sgml-r--r--r-- 1 skud skud 10647 Nov 9 00:36 help.sgml-r--r--r-- 1 skud skud 2280 Nov 8 21:15 intro.sgml-r--r--r-- 1 skud skud 10883 Nov 8 23:12 loggingin.sgml-r--r--r-- 1 skud skud 8810 Nov 2 16:00 processes.sgml-r--r--r-- 1 skud skud 24875 Nov 9 00:06 shell.sgml

-r--r--r-- 1 skud skud 1739 Nov 8 23:14 unixbasics.sgml-r--r--r-- 1 skud skud 11751 Nov 2 15:51 usersandgroups.sgml-r--r--r-- 1 skud skud 6528 Nov 8 22:25 whatisunix.sgml

Showing hid den filesTo show all files, includinghiddenfiles (which begin with a dot),usels -a.

. .project b.txt myfile.txt spelling.txt

.. .tcshrc email.txt phonelist.txt

.plan a.txt flavour.txt quotes.txt

Thefile called. (dot) is thecurrentdirectory;thefile called.. (dotdot) is thedirectoryabove thecurrentone.You canreferto thesedirectoriesin commandslike ls .. if youwish.

You cancombinethetwo optionsby usingls -al or ls -la (theorderis unimportant).

drwxr-sr-x 2 train01 staff 1024 Nov 9 11:44 .drwxrwsr-x 13 root staff 1024 Nov 3 09:11 ..

-rw-r--r-- 1 train01 staff 77 Nov 3 15:13 .plan-rw-r--r-- 1 train01 staff 39 Nov 3 15:19 .project-rw-r--r-- 1 train01 staff 42 Nov 5 09:42 .tcshrc-rw-r--r-- 1 train01 staff 63 Nov 3 11:01 a.txt-rw-r--r-- 1 train01 staff 40 Nov 3 11:01 b.txt-rw-r--r-- 1 train01 staff 165 Nov 5 10:17 email.txt

-rw-r--r-- 1 train01 staff 769 Nov 5 10:17 flavour.txt-rw-r--r-- 1 train01 staff 89 Nov 3 11:01 myfile.txt-rw-r--r-- 1 train01 staff 136 Nov 5 10:17 phonelist.txt-rw-r--r-- 1 train01 staff 5726 Nov 3 11:04 quotes.txt-rw-r--r-- 1 train01 staff 760 Nov 5 10:17 spelling.txt

Readme: For other options for the ls command, read the manpage by typing man ls .

Advanced: There are only a couple of letters of the alphabet which aren’t options to ls - can youfind what they are?

40

Page 41: Unix Basics - UNAM

Chapter 6. Files and directories

Exercise

1. Practicelisting files in your homedirectoryusingvariousoutputformats:

• normal

• long format

• show hiddenfiles

• long formatwith hiddenfiles

2. Readthemanualpagefor ls andtry someof theothercommandline switches

The Unix system’ s file structureUnix systemshave atree-likefile structure,similar to DOSor Windowssystems(whichwere,in aroundaboutway, basedon Unix).

Thebaseof this treeis the"root directory"which is referredto as/ ("slash").Otherdirectoriesbranchout of therootdirectory, andeachlevel of branchingis separatedby aslash,in a similarwayto how DOS/Windowsdirectoriesareseparatedby abackslash(\).

Typically, thefollowing directoriescanbefoundundertherootdirectoryof aUnix system:

Table6-1.Unix dir ectoriesand their contents

Directory name Contents

/bin Binaryfiles (executables)

/etc System-wideconfigurationfiles

/dev Device files

/home Userhomedirectories

/lib Library files

/sbin Superuserbinaryfiles

/tmp Temporaryfiles

/usr Filesfor users

/var Variousstuff (logfiles,incomingmail spools,etc)

/opt Optionalpackages,oftenmajorsoftwarepackagesprovidedby thevendorasadd-onsto thesystem

41

Page 42: Unix Basics - UNAM

Chapter 6. Files and directories

Viewing files

The cat commandThecat commandcanbeusedto print a file to screen.

Note: Its name is short for "catenate", which (in Unix terms) means to print out a file."Concatenate" means to join together two or more files (or other text) to form one big one.

% cat mytextfile

Advanced: The output of cat can be redirected into another file or piped through anothercommand.

% cat mytextfile > newtextfile% cat mytextfile ��� newtextfile% cat mytextfile | mail [email protected]

Exercise

1. Try thiscommand(therearesomefiles in yourhomedirectorywhich youcanuse).

More or lessFor fileswhich arelongerthana screenful,you canusethemore or lesscommandsto view them.

Themore commandpresentsthefile a screenfulat a time.To scroll down a page,pressSPACE.

The lesscommandis anextendedversionof more, socalledbecauseit allowsyou to scroll backinthedocumentaswell asforward.Somesystemsdonot have the lesscommand,but mostmodernUnix variantsdo have it.

Exercise

1. Try usingmore andlessto view files in yourhomedirectory.

42

Page 43: Unix Basics - UNAM

Chapter 6. Files and directories

Copying filesTo copyfiles,usethecp command.Thiscommandtakesmultiplearguments- all exceptthelastargumentarethefile(s)you wantto copy, andthelastargumentis whereyou wantto copythemto.If you specifymorethanonefile to copy(by usingwildcards/globs)thenyoumustcopythemto adirectory. Wildcardsandglobsareexpandedby theshellbeforebeingpassedto thecp command.

% cp myfile.txt myfile.bak% cp myfile.txt myotherfile.txt yetanother.txt backups/% cp *.bak backups/

Exercise

1. Practicecopyingyourfiles usingthecp command

Moving or renaming filesTo move or renamefiles,usethemv command.Thiscommandtakesargumentsjust like cp, howeverthenamesof files to bemovedmaybedirectories,in whichcasetheentiredirectoryandall itscontentswill bemovedto thenew location.

% mv myfile.txt myfile.bak% mv myfile.bak myotherfile.bak yetanother.bak backups/% mv *.bak backups/% mv backups/ /tmp/

Exercise

1. Practicemoving or renamingyourfiles usingthemv command

Deleting filesTo deletefiles,usethe rm . This commandtakesany numberof arguments,which arethefiles (orglobpatternsof groupsof files) youwish to delete.Notethatyoucannotdeletedirectoriesusingrm(at least,not withoutusingspecialswitches);you wouldusethermdir command(which we willencountershortly)for that.

% rm *.bak

% rm *.bak backups/ /tmp/*.bak /tmp/backups/*

43

Page 44: Unix Basics - UNAM

Chapter 6. Files and directories

Note: There is no undelete command in Unix. Once you delete a file, you cannot get it backexcept by restoring from backups. Therefore, it is often a good idea to alias rm to rm -i - this willask you for confirmation before deleting files.

Exercise

1. Practicedeletingfiles usingtherm command.Don’t deleteanything you’renotcertainabout--perhapsonly deletefiles you’vecreatedyourselfduringthepreviouspartsof this trainingmodule

2. Justto beon thesafeside,createa shellaliassothatwhenyoutyperm it actuallyrunsrm -iandasksyou for confirmationbeforedeleting.Look backatChapter4 (TheShell)for detailsonhow to do this.

Changing directoriesChangingdirectoriesunderUnix is similar to DOS.Thecommandusedto changedirectoriesis cd.

Table6-2.Changing dir ectories

To do this... Syntax example

Changeto a specificdirectory cd /usr/local/bin

Changeto onedirectoryup thetree cd ..

Changeto two directoriesup thetree cd ../..

Changeto your homedirectory cd or cd ~

Changeto a directoryunderyourhomedirectory cd ~/backup

Changeto anotheruser’shomedirectory cd ~username

Exercise

1. Practicechangingdirectoryusingthedifferentformsof thecd command

2. Doesyourshellpromptshow you which directoryyou’rein? If not, look backat Chapter4 (TheShell)to seehow to configureit to show you thecurrentdirectory.

3. Changeto /usr/doc and/or/usr/local/doc andseewhatdocumentationis availableonyoursystem.

44

Page 45: Unix Basics - UNAM

Chapter 6. Files and directories

Finding your current director yTo find out whatdirectoryyou arecurrentlyin, usethepwd command.Thisstandsfor "printworkingdirectory"andprintsout thenameof thecurrentdirectoryto thescreen.

% pwd/home/train01

Exercise

1. Practiceusingthepwd command.

Creating and deleting directoriesTo createa new directory, usethemkdir command.

% mkdir documents

To deletea directory, usethermdir command.

% rmdir documents

Advanced: Note that this will not work if the directory has files in it. If you want to delete adirectory and everything in it, type rm -rf dirname

Exercise

1. Makea directorycalledbackups in your homedirectoryandcopyall your text files into it.

Chapter summar y

• UnderUnix, almosteverythingis a normalfile which canbeviewedandmanipulatedin commonways

• The ls commandis usedto list files.Commandline switchescanbeusedto modify thebehaviourof thiscommand.

45

Page 46: Unix Basics - UNAM

Chapter 6. Files and directories

• Thepwd commandcanbeusedto show thecurrentdirectory.

• Thecat commandis usedto print files to thescreen

• moreandlessareusedto print files to thescreena pagefulata time.

• Thecp, mv andrm commandscanbeusedto copy, move/rename,anddeletefiles respectively.

• Thereis no undeletecommandin Unix -- beware!

• Themkdir commandcanbeusedto createdirectoriesandthermdir to remove them.

46

Page 47: Unix Basics - UNAM

Chapter 7. Editing

In this chapter ...In thischapteryou will learnhow to usethevi editorandbeintroducedbriefly to othereditorswhichmaybeavailableon Unix systems.

The vi editorThemostcommoneditoron Unix systemsis vi. Althoughits commandsandsyntaxarequitedifficult to learn,it is a verypowerful text editorwhichwill allow you to write or programveryefficiently. Also, thefact thatvi is oftentheonly editoronmany Unix systemsmeansit is essentialtoknow at leastthebasics.

Readme: The vi editor is described in detail in chapter 8 of the textbook, starting on page 321.You can also find more information by typing man vi , which may point you to additional onlinedocumentation.

To usethevi editor, simply typevi filename.

You will seesomethinglike this:

~~

~foo: new file: line 1

... avertical row of tildes,andonthebottomanindicationof thefile you areeditingandsomestatusinformationsuchastheline youareon.

Command and Inser t modesWhenyou first getinto vi, you arein whatis known as"commandmode".In thismode,youcantypevariouscommandsto affecta file you’reediting,or you canenter"insertmode"to inserttext into thefile.

To enter"insertmode",typei. Thisallowsyouto entertext.

Typea sentencesuchas"Hello, world" thenpressESC to returnto commandmode.

Note: You can always type ESC to return to command mode. It’s a good idea to get into the habitof doing this if you’re not sure what mode you’re in.

47

Page 48: Unix Basics - UNAM

Chapter 7. Editing

You canseewhatmodeyou’re in by typing :set showmode(you’ll needto bein commandmodetodo this,sotypeESC followedby a colon,etcetera.Seethesectionon Settings,below, for moreoptionsyoucanset.

Table7-1. Inserting

Command Effect

i Insertbeforecursor

I Insertatstartof line

a Insertaftercursor

A Insertatendof line

o Opena line below thecurrentline

O Opena line above thecurrentline

Movement commands

Table7-2.Movementcommands

Command Effect

j Godown oneline

k Goup oneline

h Go left onecharacter

l Goright onecharacter

^F Goforwardonescreen

^B Gobackonescreen

^ Move to beginningof text on thecurrentline

$ Move to theendof thecurrentline

{ Move to beforethecurrentparagraph

} Move to afterthecurrentparagraph

G Goto theendof thefile

nG Goto linen

Most movementcommandscanbeprefacedby a number, andwill berepeatedthatnumberof times.For instance,10j will go down tenlines.

Note: While some newer systems will allow you to use arrow keys to move around in vi , it isnevertheless a good idea to get used to using the hjkl navigation keys in case you encounter asystem where the arrow keys do not work. It will also allow you to edit files faster if you are a

48

Page 49: Unix Basics - UNAM

Chapter 7. Editing

touch typist, as you will not need to move your hands away from the home keys to navigate.

Simple text editing commands

Table7-3.Simple text editing commands

Command Effect

x Deletethecharacterunderthecursor

dd Deletethecurrentline

dw Deleteto theendof thecurrentword

u Undolastcommand

. Repeatlastcommand

Like themovementcommands,mostof thesesimpletext editingcommandscanbemadeto repeatby prefacingthecommandwith a number. For instance,6dd will deletesix lines.

Searching and replacing

Table7-4.Searching and replacing

Command Effect

/string Searchfor string

n Findnext occurrenceof string

N Findpreviousoccurrenceof string

:s/string/replacement Replacefirst instanceof string on thisline with replacement

:s/string/replacement/g Replaceall instancesof string on thisline with replacement

:%s/string/replacement/g Replaceall instancesof string in theentire file with replacement

Cutting and pastingTheclipboardin vi is referredto asthe"buffer". Text which is cutor copiedis storedin thebufferuntil anothercutor copyoperationoverwritesit. You canpasteasoftenasyou wantfrom thebuffer.

Thedd, dw andx commandsfrom theprevioussectionall placethedeletedtext into thebuffer. They

49

Page 50: Unix Basics - UNAM

Chapter 7. Editing

areequivalentto "cut".

In vi, "copying" is known as"yanking" text into thebuffer. To yanktext, thefollowing commandsmaybeused:

Table7-5.Yanking

Command Effect

yy Yankthecurrentline into thebuffer

yw Yankthewordunderthecursorinto thebuffer

To pastethecontentsof thebuffer, thefollowingcommandsmaybeused:

Table7-6.Pasting

Command Effect

p Pasteafterthecursor

P Pastebeforethecursor

Some fun and useful commands

Table7-7.Somefun and useful commands

Command Effect

~ Changethecaseof a character(uppercasebecomeslowercase,andvice versa)

J Jointwo linestogether

Saving and quitting

Table7-8.Saving and quitting

Command Effect

:w Write (save) thefile

:w filename Write (save) asfilename

:wq Write andquit

:q! Quit withoutwriting

50

Page 51: Unix Basics - UNAM

Chapter 7. Editing

SettingsTherearea numberof settingsyoucanseteitherfrom commandmodeor from a configurationfilecalled.exrc which livesin your homedirectory.

Exercise

1. Openthefile learnvi.txt in vi anduseit to practiseusingtheeditor

Variants of viTherearevariantsof vi suchasvim, nvi andelvis, all of which provide additionalfunctionalityontop of thebasicvi commands.

Other editor sHerearesomebrief instructionsfor othereditorswhich youmayfind on Unix systems,in theformof brief "cheatsheets"for eachone.

Table7-9.Layout of editor cheatsheets

Running Recommendedcommandline for startingit.

Using Reallybasichowto. This is notevenanattemptata detailedhowto.

Exiting How to quit.

Gotchas Odditiesto watchfor.

emacs

Running

% emacs

Using

Complicated;seethe"Help" facility by typing CTRL -H.

51

Page 52: Unix Basics - UNAM

Chapter 7. Editing

Exiting

CTRL -X thenCTRL -C.

Gotchas

Thiseditor takesa lot of systemresourcesto run,asit containsmany extra functionsotherthantextediting,andafull-blown programminglanguagefor writing new functions.

Readme: The emacs editor is described in chapter 7 of the textbook, starting on page 302.

pico

Running

% pico -w filename

Using

• Cursorkeysshouldwork to move thecursor.

• Typeto inserttext underthecursor.

• Themenubarhas^X commandslisted.This meansholddown CTRL andpresstheletterinvolved,eg CTRL -W to searchfor text.

• CTRL -O to save.

Exiting

Follow themenubar, if you arein themidstof a command.UseCTRL -X from themainmenu.

Gotchas

Line wrapsareautomaticallyinsertedunlessthe-w flag is givenon thecommandline. Thisoftencausesproblemswhenstringsarewrappedin themiddleof codeandsimilar. \\ \hline

Help

52

Page 53: Unix Basics - UNAM

Chapter 7. Editing

CTRL -G from themainmenu,or just readthemenubar.

joe

Running

% joe filename

Using

• Cursorkeys to move thecursor.

• Typeto inserttext underthecursor.

• CTRL -K thenS to save.

Exiting

• CTRL -C to exit withoutsave.

• CTRL -K thenX to save andexit.

Gotchas

Nothingin particular.

Help

CTRL -K thenH.

jed

Running

% jed

53

Page 54: Unix Basics - UNAM

Chapter 7. Editing

Using

• Defaultsto theemacsemulationmode.

• Cursorkeys to move thecursor.

• Typeto inserttext underthecursor.

• CTRL -X thenS to save.

Exiting

CTRL -X thenCTRL -C to exit.

Gotchas

Nothingin particular.

Help

• Readthemenubarat thetop.

• PressESC then? thenH from themainmenu.

Chapter summar y

1. Thevi editor is themostcommontext editorunderUnix andcanbefoundon mostsystems.

2. Othereditorssuchasemacs, pico andotherscanbefoundon somesystems.

54

Page 55: Unix Basics - UNAM

Chapter 8. Users, groups and permissions

In this chapter ...As mentionedin Chapter2 (Whatis Unix?),Unix is amulti-useroperatingsystem.Thischapterdealswith Unix’sconceptsof users,groupsof users,andthepermissionswhich allow themto readandmodify files,andrun programs.

Users

The /etc/pass wd fileUserson a Unix systemarelistedin the/etc/passwd file. This is thefile which is lookedatwhenyou log in, to makesurethatyou areavalid userof thesystem.Eachline of the/etc/passwd filelookssomethinglike this:

fred:0xw/4Pj0nYrBc:1000:1000:Fred Foonly:/home/fred:/usr/bin/tcsh

Thefieldsin the/etc/passwd file areseparatedby colons(:). In order, they are:

Table8-1.Fields in /etc/passwd

Field Description

username theusernamewhich theuserusesto login

password theuser’spassword(in encryptedform)

uid theuserID (anumericidentifierfor eachuser)

gid theuser’sdefaultgroupID (groupsarediscussedlater)

GECOSfield textual informationabouttheuser(usuallyincludingtheuser’s realname)

homedirectory theuser’shomedirectory, wherethey will findthemselvesdirectlyafterloggingin

defaultshell theshell to run whentheuserlogsin

who, whoami and wYou canfind out whatusersareloggedinto a systemby usingthewho command.

55

Page 56: Unix Basics - UNAM

Chapter 8. Users, groups and permissions

% who

skud ttyp0 Oct 19 23:07 (stan29.zip.com.au)penny ttyp3 Oct 19 23:43 (vurt.net)thorfinn ttyp5 Oct 19 21:48 (mycroft.tertius.net.au)ajc ttyp6 Oct 14 13:47 (203.18.243.205)

Theoutputof this commandshowswho’s loggedin, whatvirtual terminalthey areconnectedto,whenthey loggedin, andwhatsystemthey’re loggedin from.

You canalsotypewho am i to find outwho you areloggedin as(the"am i" is a specialkind ofargumentto who).

% who am ivitaly!skud ttyp0 Oct 19 23:07 (stan29.zip.com.au)

Notethatthesystemnameis alsogivenin thisoutput;in thiscase,"vitaly".

Thecommandwhoami is differentfrom who am i, andsimply showsyouyour username:

% whoamiskud

Thew shows a list of usersloggedin andwhatthey’redoing:

% w3:43pm up 8 days, 4:33, 6 users, load average: 1.05, 0.79, 0.46

USER TTY FROM LOGIN@ IDLE JCPU PCPU WHATskud ttyp0 :0 Sat 8pm 1.00s 15.06s 0.21s wskud ttyp3 :0 Sun12pm 9:28 3.34s 3.13s ssh skud hiro.nskud ttyp5 :0 Mon10am 8.00s 0.91s 0.09s man w

Exercise

1. Practiceusingthewho, whoami andw commands.

The fing er commandThefinger givesmoreinformationabouta user. As well asshowing informationfrom the/etc/passwdfile andwhether(andhow many times,andfrom where)they’re loggedin, it canprintout thecontentsof certainfiles theuserhascreatedto give moreinformationaboutthemself.

% finger skud

Login: skud Name:Directory: /home/skud Shell: /usr/bin/tcshOn since Tue Oct 19 23:07 (EST) on ttyp0 from stan29.zip.com.au

1 second idleOn since Tue Oct 19 22:01 (EST) on ttypf from stan29.zip.com.au

12 minutes 36 seconds idle

New mail received Thu Aug 12 11:51 1999 (EST)

56

Page 57: Unix Basics - UNAM

Chapter 8. Users, groups and permissions

Unread since Mon Aug 9 11:54 1999 (EST)

No Plan.

If you createa file called.plan (rememberingthattheleadingdotmakesit a hiddenfile) you canenterany text you like andhave it show up whensomeonefingersyou:

% finger skudLogin: skud Name:Directory: /home/skud Shell: /usr/bin/tcshOn since Tue Oct 19 23:07 (EST) on ttyp0 from stan29.zip.com.au

1 second idle

On since Tue Oct 19 22:01 (EST) on ttypf from stan29.zip.com.au12 minutes 36 seconds idle

New mail received Thu Aug 12 11:51 1999 (EST)Unread since Mon Aug 9 11:54 1999 (EST)

Plan:To finish writing the Unix Basics training course, then go to sleep.

Likewise,afile called.project is oftenusedto describea user’scurrentproject:

% finger skudLogin: skud Name:Directory: /home/skud Shell: /usr/bin/tcshOn since Tue Oct 19 23:07 (EST) on ttyp0 from stan29.zip.com.au

1 second idleOn since Tue Oct 19 22:01 (EST) on ttypf from stan29.zip.com.au

12 minutes 36 seconds idleNew mail received Thu Aug 12 11:51 1999 (EST)

Unread since Mon Aug 9 11:54 1999 (EST)Project:Training for Netizen

Plan:To finish writing the Unix Basics training course, then go to sleep.

You canalsofingerusersonremotesystemsby usingfinger [email protected], howevermany systemsaresetupto refusefingerrequestsfrom remotesystems.

Exercise

1. Create.plan and.project files in yourhomedirectory. Usethefinger commandto seetheiroutput.

Groups

57

Page 58: Unix Basics - UNAM

Chapter 8. Users, groups and permissions

Groupsof users,suchas"staff" or "web-users"or "admin"canbecreatedby thesystemadministrator. Thesearelistedin the/etc/group file. Groupsareusedto setpermissiosnfor files,sothat(for instance)only staff cangetatdocumentsin a specialstaff directory.

The /etc/gr oup fileThe/etc/group containslineswhich look like this:

staff:x:100:skud,fred,mary,bill

Thefieldsaregroupname,password(usuallynot used),numericgroupID, anda comma-separatedlist of theuserswho arein thatgroup.

The groups commandTo find out which groupsyou areamemberof, usethegroupscommand.

% groupsskud staff www admin

Exercise

1. Usethegroups to seewhatgroupsyou’re in.

Permissions

Finding a file’ s permissionsA file’s permissionscanbefoundby usingthelong form of the ls, i.e. ls -l:

-rw-r--r-- 1 skud skud 391 Nov 2 21:12 changes.sgml-r--r--r-- 1 skud skud 13938 Nov 9 11:09 editing.sgml

-rw-r--r-- 1 skud skud 9238 Nov 9 11:42 filesanddirectories.sgml-r--r--r-- 1 skud skud 973 Oct 20 00:45 furtherreading.sgml-r--r--r-- 1 skud skud 10647 Nov 9 00:36 help.sgml-r--r--r-- 1 skud skud 2280 Nov 8 21:15 intro.sgml-r--r--r-- 1 skud skud 10883 Nov 8 23:12 loggingin.sgml

-r--r--r-- 1 skud skud 8810 Nov 2 16:00 processes.sgml-r--r--r-- 1 skud skud 24875 Nov 9 00:06 shell.sgml-r--r--r-- 1 skud skud 1739 Nov 8 23:14 unixbasics.sgml-r--r--r-- 1 skud skud 11751 Nov 2 15:51 usersandgroups.sgml

58

Page 59: Unix Basics - UNAM

Chapter 8. Users, groups and permissions

-r--r--r-- 1 skud skud 6528 Nov 8 22:25 whatisunix.sgml

Therearetencharactersat thestartof eachline which describethefile’s typeandpermissions.

Thefirst charactershows whethertheitem listedis a directoryor a symboliclink. If it is adirectory,theletterd will appearthere.If it is a link, theletterl will appearthere.Otherwiseit will simplyshow a hyphen,meaningthatthefile is just anormalfile.

Thenext ninecharactersarein threegroupsof three.Thegroupsare"owner", "group",and"world"anddescribethepermissionseachof thosegroupsof usershaswith regardto thefile. Thepermissionsthatthey canhave areany of "read","write" and"execute".

Theownerof a file is thepersonwhoseusernameappearsin thefourth columnof the ls -l output.Thegroupof a file is thegroupnamewhich appearsin thefifth columnof theoutput.

"Read"permissionmeansthatsomeonemaylook at thecontentsof a file but not changethem.

"Write" permissionmeansthatsomeonemaychangethecontentsof a file, or mayrenameit, deleteit, etc.

"Execute"permissionmeansthata someonehastheability to run thatfile asanexecutableprogram.

Let’s look atanexample:

-rw------- 1 fred staff 84354 Oct 17 21:09 myfile.txt

-rw-r----- 1 fred staff 4705 Aug 1 15:37 meeting_minutes.txtdrwxr-xr-x 15 fred staff 2048 Oct 28 15:00 public_html

Thefirst file, myfile.txt, is readableandwritableby Fredandnobodyelse.

Thesecondfile, meeting_minutes.txt,is readableandwritableby Fred,andalsoreadableby anyotheruserin thestaff group.

Thethird file is actuallya directory, andis probablythedirectorycontainingFred’spersonalhomepage(public_html is thecustomarynamefor a directoryfor a user’shomepage).It is readableandexecutableby everyone(fred,his group,and"other")becausea directorymustbeexecutabletoallow peopleto changeinto thatdirectory. It is alsowritableby Fred,sothathecancreatenew filesin thatdirectory.

Changing a file’ s permissionsA file’s permissionsarechangedby usingthechmod command.Thiscommandhastwo formsofsyntax,oneof whichuseseasily-rememberedabbreviations,andoneof which usesoctal(base-8)notationfor permissions.

Theeasierform usesthefollowing lettersfor thegroupsof usersto whompermissionsapply:

Table8-2.Abbreviations for groups

User u

59

Page 60: Unix Basics - UNAM

Chapter 8. Users, groups and permissions

Group g

Other o

All a

Table8-3.Abbreviations for permissions

Readable r

Writable w

Executable x

Herearesomeexamplesof usage:

Makeafile readableby everyone(thefollowing two commandsareequivalent):

% chmod a+r myfile.txt

% chmod +r myfile.txt

Makeafile writableby theuserandgroup:

% chmod ug+w myfile.txt

Remove executionpermissionsfor groupandother:

% chmod go-x myscript.sh

Advanced: The octal form of this command uses three octal digits to represent the states of theowner, group and world permissions. "Readable" is equal to 4, "writable" is 2, and "executable" is1. Simply add together the permissions for each group.

For instance, to make a file readable and writable by the owner only, use chmod 600 myfile .txt .To make it readable and executable by everyone, but only writable by the owner, chmod 755myfile .txt .

Chapter summar y

1. Userson aUnix systemarespecifiedin the/etc/passwd file

2. Thewhoami showsyou whoyou’re loggedin as.

3. Thewho andw commandscanshow youwho’s loggedin to thesystemat themoment.

60

Page 61: Unix Basics - UNAM

Chapter 8. Users, groups and permissions

4. Thefinger commandshowsyou moreinformationaboutuserson thesystem(or on anothersystemconnectedto thenetwork)

5. You cancreatefilescalled.plan and.project to customiseyourfinger output

6. Groupsof usersarespecifiedin the/etc/group file

7. You canfind out whatgroupsyou arein by usingthegroupscommand

8. A file canhave read,write andexecutepermissionssetfor eachof "user","group"and"other"

9. A file’spermissionscanbechangedusingthechmodcommand

61

Page 62: Unix Basics - UNAM

Chapter 9. Processes

In this chapter ...Multi-taskingoperatingsystemssuchasUnix areableto runmorethanoneprogram(or "process")simultaneously. Thischapterexploresthecommandsusedfor managingprocessesunderUnix.

What is a process?As mentionedearlier, Unix is a "multi-tasking"operatingsystem.Thismeansthatit canrun manyprogramsor applicationssimultaneously.

Unix refersto eachcurrently-runningprogramasa"process".Everyprocesshasa processid (pid)which is a number. Thefirst processto runwhenthesystemstartsup is processnumber1, andsubsequentprocessesaregivenconsecutively largernumbers.

Every processrunningis associatedwith a user-- usuallytheuserwhostartedtheprocess.Processesmayalsohave a"controlling terminal"-- thevirtual terminalfrom which theprocessstarted,andtowhich its inputandoutputareattached.However, someprocessesdo not have a controllingterminal;thesearecalled"backgroundprocesses"andwe’ll look at themlater.

Listing processes - the ps commandYou canusetheps commandto list processes.Hereis asampleprocesslisting:

yt:~> psPID TTY STAT TIME COMMAND12539 p3 S 0:00 -csh12835 p0 S 0:00 -csh13072 p4 S 0:00 -csh

13141 p5 SW 0:00 (tcsh)13198 p3 S 0:01 vim processes.sgml13203 p6 S 0:00 -csh13204 p6 R 0:00 ps

Theps withoutany switchesor otherargumentsshowsprocesseswhich arebeingrun by you,whichhave a controllingterminal.(We’ll find outaboutprocesseswith nocontrollingterminallater.) ThePID listedis the"processID" -- a numericidentifierwhich uniquelyidentifieseachprocessrunningon thesystem.

62

Page 63: Unix Basics - UNAM

Chapter 9. Processes

Exercise

1. Usethepscommandto seewhatprocessesyou have running.Canyou identify themall?

Command line switc hes to psThecommandline switchesto psvary significantlybetweendifferentflavoursof Unix. However,sincemostsystemssupportBSDstyleswitches,thosearetheoneswhich will bedescribedhere.

Table9-1.BSD-stylecommandline switchesfor ps

Switch Meaning

l long format

a show all processes(not just yourown)

u userformat;showsusernameandstarttime

x show processeswith nocontrollingterminal

w wide listing (ww makes it even wider)

Thefollowing processlisting formatis very common,but tendsto producea lot of output.Pipeitsoutputthroughlessor someotherfilter to ensurethatyou canseeimportantinformation.

% ps auxw

USER PID %CPU %MEM SIZE RSS TTY STAT START TIME COMMANDdaemon 150 0.0 0.0 1104 0 ? SW Oct 25 0:00 (portmap)mail 14902 0.0 0.0 1712 0 ? SW Oct 26 0:01 (sendmail)root 1 0.0 0.1 1016 72 ? S Oct 25 0:03 init [2]root 2 0.0 0.0 0 0 ? SW Oct 25 0:13 (kflushd)root 3 0.0 0.0 0 0 ? SW Oct 25 0:11 (kupdate)

root 4 0.0 0.0 0 0 ? SW Oct 25 0:00 (kpiod)root 5 0.0 0.0 0 0 ? SW Oct 25 0:31 (kswapd)root 120 0.0 0.5 1348 212 ? S Oct 25 0:05 /sbin/syslogdroot 122 0.0 0.0 1288 0 ? SW Oct 25 0:00 (klogd)root 142 0.0 0.1 996 48 ? S Oct 25 0:00 /sbin/kerneldroot 154 0.0 0.0 1304 0 ? SW Oct 25 0:00 (inetd)

root 182 0.0 0.1 1020 56 ? S Oct 25 0:02 /usr/sbin/gpm -m /dev/psaux -t ps2 -l "a-zA-Z0-9_.:~/\300-\326\330-\366\370-\377"root 245 0.0 0.0 1904 0 ? SW Oct 25 0:00 (safe_mysqld)root 252 0.0 0.1 4040 44 ? S N Oct 25 0:00 (mysqld)root 261 0.0 0.1 2180 52 ? S Oct 25 0:01 /usr/sbin/apacheroot 272 0.0 0.0 1136 0 2 SW Oct 25 0:00 (getty)

Advanced: The most popular Unix variant which uses completely different switches for ps isSolaris. To find out about the command line switches on that (or any other) flavour of Unix, typeman ps . Note that a BSD-style ps is available on Solaris systems in /usr/ucb/ps

63

Page 64: Unix Basics - UNAM

Chapter 9. Processes

Exercise

1. Experimentwith theeffectsof someof thecommandline switches

2. If theoutputis too long for you to readeasily, pipeit throughthe lesspagerby typingpsswitches | less

Killing processesYou cankill any processwhich youown (but not thoseownedby otherusers)by usingthekillcommand:

% psPID TTY STAT TIME COMMAND12539 p3 SW 0:00 (tcsh)13141 p5 SW 0:00 (tcsh)13198 p3 S 0:07 vim processes.sgml13279 p6 R 0:00 ps

% kill 13198% ps

PID TTY STAT TIME COMMAND12539 p3 SW 0:00 (tcsh)13141 p5 SW 0:00 (tcsh)

13279 p6 R 0:00 ps

You cansendothersignalsto processesusingthekill command’s optionalswitches.You cangiveansignalnameasanoptionalswitch,or a signalnumber. Someof thecommonsignalnamesandnumbersarelistedin themanualpagefor kill , or you cangeta list of availablesignalnameswithkill -l

% kill -lHUP INT QUIT ILL TRAP ABRT BUS FPE KILL USR1 SEGV USR2 PIPE ALRM TERM STKFLTCHLD CONT STOP TSTP TTIN TTOU URG XCPU XFSZ VTALRM PROF WINCH POLL PWR UNUSED

Themostcommonlyusedsignalis KILL, which forcesa processto bekilled evenif a normalkillcommandcannotkill it. This is oftenusefulif a programhas"hung"andwill not respondtoanything.Thesignalnumberfor KILL is 9, thereforethefollowing two commandsareequivalent:

% kill -KILL 13198% kill -9 13198

64

Page 65: Unix Basics - UNAM

Chapter 9. Processes

Exercise

1. Try killing someof your processes(anddon’t besurprisedif it logsyouout whenyou kill yourown shell!)

2. Canyou kill otherpeople’sprocesses?

Backgr ound processes and job contr ol

Running a process in the backgr oundOnUnix, it is possibleto runprocessesin thebackground.This meansthattheprocessbecomesdetachedfrom its controllingterminalandrunsmore-or-lessinvisibly to theuser.

To starta processrunningin thebackground,simplyputanampersand(&) afterthecommandonthecommandline.

% cp -r * /tmp &[1] 13319

Exercise

1. Runa vi editorsessionin thebackground

Listing running jobsTo geta listing of runningjobs,usethe jobs command.

% jobs

[2] + Suspended (tty output) top[3] - Running tar -c /www > www.tar

Note: Note that a job is not the same as a process. A job may have many different processesassociated with it. For instance, if you create a pipeline on the command line (that is, connectmultiple programs together using pipes) there will be several processes running, but theyconstitute only one job.

65

Page 66: Unix Basics - UNAM

Chapter 9. Processes

Exercise

1. List yourcurrently-runningjobs.Do youseeyourvi sessionthere?

Bringing a backgr ounded process to the foregr oundAs youcansee,whenyou run aprogramin thebackgroundit will tell you theprocessID it hasbeengiven,andalsoa job number.

Note: The Bourne Shell (sh ) does not have job control; this section assumes you are using amore featureful shell such as bash , tcsh , csh or ksh .

This job numberallowsyouto bringa job to theforegroundusingthefg command.Thefollowingcommandwouldbring job number1 to theforeground:

% fg %1

Exercise

1. Bring yourvi sessionto theforegroundusingfg

Backgr ounding an alread y-running jobLastly, if youwish to sendanalready-runningprogramto thebackground,you candothis by firstpressingCTRL -Z to suspendit, thentyping thebg command:

% yt:~/work/training/unixtools> tar -c /www > www.tar

(CTRL-Z is pressedat thispoint)

Suspended% bg[3] tar -c /www > www.tar &

Exercise

1. Putyourvi sessioninto thebackgroundusingCTRL -Z andbg

66

Page 67: Unix Basics - UNAM

Chapter 9. Processes

Killing a running jobYou canalsokill a runningjob with thekill by giving it thejob numberasanargument:

% kill %3[3] - Terminated tar -c /www > www.tar

Exercise

1. Kill off yourbackgroundedvi sessionusingkill

2. How elsecouldyou have killed theprocess?

Chapter summar y

1. Processescanbelistedusingtheps command.

2. A job canbestartedin thebackgroundby addinganampersand(&) to theendof thecommandline

3. Runningjobscanbelistedusingthe jobs command

4. A backgroundedjob canbeforegroundedusingfg %jobnumber

5. An already-runningjob canbebackgroundedusingCTRL -Z

6. A processcanbekilled usingthekill process-id command

7. A job canbekilled usingthekill %jobnumber command

67

Page 68: Unix Basics - UNAM

Chapter 10. About Lin ux

What is Lin ux?Linux is anoperatingsystembasedon Unix, developedby a FinnishmannamedLinusTorvaldsanda worldwidecommunityof developers.

Linux is releasedunderan"opensource"licensecalledtheGPL (GNU PublicLicense),whichallows thelicenseeto:

• Obtainthesoftwarefor no cost,or for thecostof media(eg CD copying)

• Likewiseobtainsourcecodeto thesoftware

• Modify thesoftware

• Redistributethesoftware,providing thatit retainsthesamelicense

Linux hasa significantminority shareof theoperatingsystemmarket,andis expectedby manyindustryanalyststo grow to a majority sharein thenext few years.

TheLinux operatingsystemitself containsvery few tools,applications,or user-friendly elements.For this reason,many companiesor non-profitventureshave chosento packagetheLinux operatingsystemwith a collectionof othersoftware.Thesepackagedsoftwarecollectionsarecalled"Linuxdistributions",andinclude:

• RedhatLinux (http://redhat.com/)

• Debian/GNULinux (http://debian.org/)

• CalderaOpenLinux(http://www.calderasystems.com/)

• TurboLinux(http://www.turbolinux.com/)

• SuSELinux (http://www.suse.com/)

In total, thereareover a hundredLinux distributions.Eachtargetsa differentpartof themarket.Forinstance,CalderaOpenLinuxis renownedasbeingveryeasyto use;TurboLinuxspecialisesinsupportingAsiancharactersetssuchasJapanese;SuSEis very popularin Europe;Redhattargetcorporatedesktopusers;Debian/GNULinux requiresall its softwareto meetcertainlicensingstandardsandtendsto appealto moretechnicalusers.

Hardware requirementsLinux canrunon many kindsof hardware,includingIntel-basedPCs,Macintoshhardware,DEC/CompaqAlpha hardware,andmore.Thissectiondealsonly with Intel-basedPChardware.

68

Page 69: Unix Basics - UNAM

Chapter 10. About Linux

Althoughpeoplewill tell you thatLinux will runon just aboutany hardware,in realtermsyou needat leasta 386,or preferablya 486or better. To useany kind of graphicaluserinterface,youwill wanta high-end486or a low-endPentium.

Recommended: Pentium 100MHz or better

In termsof RAM, you will probablywantat least8Mb for anon-graphicalsetup,or 32Mbfor asetupwith a graphicaluserinterface.You canrun a graphicalinterfaceon lessmemory, but it will bepainfully slow.

Recommended: 32-64Mb of memory

A full Linux distributionwill usuallyrequireabouta gigabyteof diskspace,but you seldomneedtoinstall a full distribution. A verycut-down systemmayonly take100Mbof disk,or a reasonablyusablesystemwith a GUI andquitea lot of applicationsmaytakeabout500Mb. You caninstallLinux on asecondharddisk or diskpartitionto makea "dualboot" machinethatrunsbothLinuxandWindowsor anotheroperatingsystem.

Recommended: 1Gb of hard disk space

In additionto this basichardware,you will probablyalsowant:

• A 3.5" floppydrive

• A CD-ROM drive

• A modemor networkcard(for Internetaccessor LAN use)

• A 3-buttonmouse(youcanusea 2-buttonmouse,but 3-buttonis better)

• A keyboard(any kind)

• A monitorandgraphicscard(notethatsomeof thenewestaccelleratedvideocardsarenot yetsupportedby Linux)

Getting Lin uxLinux canbedownloadedfrom theInternet"for free",but keepin mind thatyou will have to payforconnectiontimeor for thedatayou download,thatthatanormalLinux distributioncanbe600Mbormore.You wouldalsoneeda CD burnerto createa CD of thedownloadeddata.

It is almostalwayseasiestto buy a Linux CD in oneof variousforms:

• CheapCDs,papersleeve,no instructions(about$2-$5)

• "Box set"versionsof Linux, usuallyincludingCDswith full instructionsin theform of a book(about$50or more)

• "Pocketbook"distributions,for exampletheAPCPocketbook,containingCDsandbrieferinstructions(about$20for 2 distributions)

Thesecanbeobtainedfrom:

69

Page 70: Unix Basics - UNAM

Chapter 10. About Linux

• SpecialistLinux businessessuchasEverythingLinux(http://www.everythinglinux.com.au)orLinux SystemLabs(http://www.lsl.com.au)

• Technicalbookshops

• Computerswapmeets

Most specialistLinux businesseswill takeordersonlineandwill acceptcreditcardsor COD.

Getting helpLinux canbedauntingfor anew user. Whenyou first install Linux, andfor yourfirst six monthsormoreof use,you will probablywantsomehelp.

Help is availablefrom variousplaces,including:

Lin ux User Groups (LUGs)Many Linux UserGroupsexist aroundAustraliaandtheworld. SomeAustralianonesinclude:

• Linux Usersof Victoria (LUV) (http://www.luv.asn.au/)

• Sydney Linux UsersGroup(SLUG)(http://www.slug.org.au/)

• HomeUnix MachineBrisbaneUsersGroup(HUMBUG) (http://www.humbug.org.au/)

A list of all AustralianLinux UserGroupscanbefoundon Linux Australia(http://www.linux.org.au/)website.Linux.org alsohasa list of LUGs aroundtheworld(http://www.linux.org/users/index.html).

Lin ux consultants and businessesMany businessesnow offer Linux supportandconsulting.Netizen(http://netizen.com.au/)is oneofthesebusinesses.Othersarelistedon theLinux Australia(http://www.linux.org.au/)website.

Online resour cesA wealthof onlineresourcesareavailable.Somegoodstartingpointsinclude:

• Linux.org (http://linux.org)

• Linux WeeklyNews (http://lwn.net)

• Linuxnewbie.org (http://linuxnewbie.org)

70

Page 71: Unix Basics - UNAM

Chapter 11. Conc lusion

What you’ ve learntNow you’vecompletedNetizen’s Unix Basicsmodule,you shouldbeconfidentin yourknowledgeof thefollowing fields:

• Whatis Unix? Unix features,differentflavoursof Unix.

• Loggingin, changingyour password,loggingout.

• TheUnix shell-- its purpose,features,anduse

• Findinghelpon Unix systems,includingmanualpagesandothersourcesof information

• Filesanddirectories;listing files in variousformats;copying,moving, renaminganddeletingfilesanddirectories;viewing files in variouswaysEditing text filesusingthevi editor

• Theconceptof usersandgroupsunderUnix; how to find informationaboutusersandgroups

• Showing andsettingfile permissionsunderUnix

• UsingUnix’sprocessesandjob control; listing processesandjobs;runningprocessesandjobsinthebackground;killing processesandjobs

• TheLinux operatingsystem;Linux’s licensebenefits;hardwarerequiredto run Linux; wheretogetLinux; whereto gethelp.

Where to now?To furtherextendyour knowledgeof theUnix andrelatedtechnologies,youmaylike to:

• Borrow or purchasethebookslistedin our "FurtherReading"section(below)

• Follow someof theURLs giventhroughoutthesecoursenotes,especiallytheonesmarked"Readme"

• PracticeusingUnix from dayto day

• Setup a homeLinux box andstartplayingwith it

• Joina Linux or Unix usergroup

• Extendyourknowledgewith furtherNetizencoursessuchas:

• Unix Tools(you areprobablytakingthismoduletomorrow)

• Perlprogramming

• AdvancedUnix

71

Page 72: Unix Basics - UNAM

Chapter 11. Conclusion

Informationaboutthesecoursescanbefoundon Netizen’swebsite(http://netizen.com.au/services/training/). A diagramof Netizen’scoursesandthecareersthey canleadto is includedwith thesetrainingmaterials.

Fur ther reading

Unix histor y and culture“The evolution of theUnix Time-sharingSystem”,DennisM. Ritchie,http://cm.bell-labs.com/cm/cs/who/dmr/hist.html

Online Unix tutorials"Unixhelp for Users"from theUniversityof Edinburgh,athttp://unixhelp.ed.ac.uk/

NormMatloff ’s"Unix Tutorial Center"at theUniversityof CaliforniaatDavis, athttp://heather.cs.ucdavis.edu/~matloff/unix.html

"A BasicUnix Tutorial" from IdahoStateUniversity, athttp://www.isu.edu/departments/comcom/unix/workshop/unixindex.html

72

Page 73: Unix Basics - UNAM

Appendix A. ASCII Pronunciation Guide

TableA-1. ASCII Pronunciation Guide

Character Pronunciation

! bang,exlamation

* star, asterisk

$ dollar

@ at

% percent

& ampersand

" double-quote

’ single-quote,tick

( ) open/closebracket,parentheses

� lessthan

> greaterthan

- dash,hyphen

. dot

, comma

/ slash,forward-slash

\ backslash,slosh

: colon

; semi-colon

= equals

? question-mark

^ caret(pron.carrot)

_ underscore

[ ] open/closesquarebracket

{ } open/closecurly brackets,open/closebrace

| pipe,or verticalbar

~ tilde (pron.“til-duh”, wiggle,squiggle)

‘ backtick

73

Page 74: Unix Basics - UNAM