Tải bản đầy đủ - 0 (trang)
Chapter 16. The Unix Crash Course

Chapter 16. The Unix Crash Course

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

regulardesktop.Thereare,however,sometasksyoucan

performonlyatthecommandline,althoughfewerwitheach

releaseofMacOSX.

Figure16-1.Top:Whatmostpeoplethinkofwhenthey

think"Macintosh"isagraphicinterface(GUI)—onethat

youcontrolwithamouse,usingiconsandmenusto

representfilesandcommands.

Bottom:TerminaloffersasecondwaytocontrolMacOS

X:acommandlineinterface,whichyouoperatebytyping

outprogrammingcommands.



ForintermediateoradvancedMacfanswithalittletimeand

curiosity,however,thecommandlineopensupaworldof

possibilities.ItletsyouaccesscornersofMacOSXthatyou

can'tgettofromtheregulardesktop.Itletsyouperform

certaintaskswithmuchgreaterspeedandefficiencythanyou'd

getbyclickingbuttonsanddraggingicons.Anditgivesyoua

fascinatingglimpseintothemindsandmoodsofpeoplewho

liveandbreathecomputers.

Ifyou'veeverdabbledinExcelmacros,experimentedwith

AppleScript,orsetupaMaconanetwork,youalreadyknow

thetechnicallevelofthematerialyou'reabouttoread.The

Unixcommandlinemaybeunfamiliar,butitdoesn'thavetobe



especiallytechnical,particularlyifyouhavesome"recipes"to

followliketheonesinthischapterandthenext.

Note:Unixisanentireoperatingsystemuntoitself.This

chapterisdesignedtohelpyoufindyourfootinganddecide

whetherornotyoulikethefeelofUnix.Ifyougetbitbythe

bug,seeAppendixEforsourcesofadditionalUnixinfo.



16.1.Terminal

ThekeyholeintoMacOSX'sUnixinnardsisaprogramcalled

Terminal,whichsitsinyourApplications Utilitiesfolder(see

Figure16-2).Terminalisnamedaftertheterminals(computers

thatconsistofonlyamonitorandkeyboard)thatstilltapinto

themainframecomputersatsomeuniversitiesand

corporations.Inthesameway,Terminalisjustawindowthat

passesalongmessagestoandfromtheMac'sbrain.

ThefirsttimeyouopenTerminal,you'llnoticethatthere'snot

muchinitswindowexceptthedate,timeandsourceofyour

lastlogin,andthecommandlineprompt(Figure16-2).



UPTOSPEED

MacOSX'sUnixRoots

In1969,BellLabsprogrammerKenThompson

foundhimselfwithsomesparetimeafterhis

mainproject,anoperatingsystemcalledMultics,

wascanceled.BellLabshadwithdrawnfromthe

expensiveproject,disappointedwiththeresults

afterfouryearsofwork.

ButThompsonstillthoughttheproject—anOS

thatworkedwellasacooperativesoftwaredevelopmentenvironment—wasapromising



idea.Eventually,heandcolleagueDennisRitchie

cameupwiththeOSthatwouldsoonbecalled

Unix(apunonMultics).BellLabssawthevalue

ofUnix,agreedtosupportfurtherdevelopment,

andbecamethefirstcorporationtoadoptit.

IntheagewhenThompsonandRitchiestarted

theirworkonUnix,mostprogrammerswrote

codethatwouldworkononlyonekindof

computer(orevenonecomputermodel).Unix,

however,wasoneofthefirstportableoperating

systems;itsprogramscouldrunondifferent

kindsofcomputerswithouthavingtobe

completelyrewritten.That'sbecauseThompson

andRitchiewroteUnixusinganewprogramming

languageoftheirowninventioncalledC.

InalanguagelikeC,programmersneedonly

writetheircodeonce.Afterthat,asoftware

Cuisinartcalledacompilercanconvertthenewly

hatchedsoftwareintotheformaparticular

computermodelcanunderstand.

Unixsoonfounditswayintolabsand,thanksto

AT&T'slowacademiclicensingfees,universities

aroundtheworld.Programmersalloverthe

worldaddedtothesourcecode,fixedbugs,and

thenpassedthosemodificationsaround.

Inthemid-1970s,theUniversityofCaliforniaat

Berkeleybecamethesiteofespeciallyintense

Unixdevelopment.Studentsandfacultythere

improvedtheUnixkernel(thecentral,essential

partoftheOS),addedfeatures,andwrotenew

Unixapplications.By1977,theyhadenough



additionalsoftwaretoreleasetheirownversion

ofUnix,thefirstofseveralBerkeleySoftware

Distribution(BSD)versions.

Asithappened,thegovernment'sDefense

AdvancedResearchProjectsAgency(DARPA)was

seekingauniform,portableOStousefortheir

growingwide-areanetwork,originallycalled

ARPAnet(andnowcalledtheInternet).

DARPAlikedUnixandagreedtosponsorfurther

researchatBerkeley.InJanuary1983,DARPA

changedARPAnet'snetworkingprotocoltoTCP/IP

—andtheInternetwasborn,runningmostlyon

Unixmachines.

Cutto1985.SteveJobsleftAppletostartNeXT

Computer,whoseNextStepoperatingsystemwas

basedonBSDUnix.WhenAppleboughtNeXTin

1996,Jobs,NextStep(eventu-allyrenamed

OpenStep)anditsTerminalprogramcamealong

withit.TheUnixthatbeatswithinMacOSX's

heartisjustthelatestrestingplacefortheOS

thatJobs'steamdevelopedatNeXT.

SothenexttimeyouhearAppletalkaboutits

"new"operatingsystem,rememberthatits

underlyingtechnologyisactuallyover35years

old.



Foruser-friendlinessfans,Terminaldoesn'tgetofftoavery

goodstart;thispromptlooksaboutastechnicalascomputers

get.Itbreaksdownlikethis:



office-mac:isthenameofyourMac(atleast,asUnix

thinksofit).It'susuallytheMac'sComputerName(asit

appearsintheSharingpaneofSystemPreferences),butit's

occasionallythenameyourMacgoesbyontheInternet.

Figure16-2.OntheWeb,MacOSX'sTerminalisone

ofthemostoften-discussedelementsofMacOSX.

Dozensofstep-bysteptutorialsforperformingcertain

taskscirculateonline,usuallywithoutmuch

annotationastowhyyou'retypingwhatyou're

typing.Asyoureadthischapter,rememberthat

capitalizationmattersinTerminal,eventhoughit

doesn'tintheFinder.AsfarasmostUnixcommands

areconcerned,Helloandhelloaretwodifferent

things.



~.Thenextpartofthepromptindicateswhatfolderyou're

"in"(Figure16-2).Itdenotestheworkingdirectory—thatis,

thecurrentlyopenfolder.(Remember,therearenoiconsin

Unix.)Essentially,thisnotationtellsyouwhereyouareas

younavigateyourmachine.

TheveryfirsttimeyoutryoutTerminal,theworking

directoryissettothesymbol~.Thattildesymbolis

importantshorthand;itmeans"yourownHomefolder."It's

whatyouseethefirsttimeyoustartupTerminal,butyou'll

soonbeseeingthenamesofotherfoldershere—office-



mac:/Usersoroffice-mac:/System/Library,forexample.

(MoreonthisslashnotationonSection1.2.4.)

Note:BeforeApplecameupwiththeuser-friendlyterm

foldertorepresentanelectronicholdingtankforfiles,

folderswerecalleddirectories.Inthischapter,you'll

encounterthetermdirectoryalmostexclusively.Inany

discussionofUnix,"directory"issimplythecorrect

term.Besides,usingatermlike"workingfolder"within

earshotofUnixgeeksislikelytogetyoulynched.

chris$beginswithyourshortusername.Itreflects

whoever'sloggedintotheshell(seetheboxonthefacing

page),whichisusuallywhoever'sloggedintotheMacatthe

moment.Asforthe$sign,thinkofitasacolon.Infact,

thinkofthewholepromptshowninFigure16-2asUnix's

wayofsaying,"OK,Chris,I'mlistening.What'syour

pleasure?"

Unlessyou'vefiddledwithTerminal'spreferences,theinsertion

pointlookslikeatallrectangleattheendofthecommandline.

Ittrotsalongtotherightasyoutype.



16.1.1.UnixPrograms

AnenormousnumberofprogramshavebeenwrittenforUnix.

Andthankstothousandsofopen-sourcedevelopers—

programmersallovertheworldwhocollaborateandmaketheir

workavailableforthenextroundofmodification—muchofthis

softwareisfreelyavailabletoall,includingMacOSXusers.

EachUnixcommandgenerallycallsupasingleapplication(or

process,asgeekscallit)thatlaunches,performsatask,and

closes.Manyofthebest-knownsuchapplicationscomewith

MacOSX.

Here'safunone:JusttypeuptimeandpressEnterorReturn.



(That'showyourunaUnixprogram:Typeitsnameandpress

Enter.)Onthenextline,TerminalshowsyouhowlongyourMac

hasbeenturnedoncontinuously.Itshowsyousomething

like:"13:096:00PMup8days,15:04,1user,

loadaverages:1.24,1.37,1.45"—meaningyourMachasbeen

runningfor8days,15hoursnonstop.

You'refinishedrunningtheuptimeprogram.The$prompt

returns,suggestingthatTerminalisreadyforwhateveryou

throwatitnext.



UPTOSPEED

bash,Terminal,andShells

OneUnixprogramrunsautomaticallywhenyou

openaTerminalwindow:bash.It'sApple's

chosenshellforMacOSX10.5.

AshellisaUnixprogramthatinterpretsthe

commandsyou'vetyped,passesthemtothe

kernel(theoperatingsys-tem'sbrain),andthen

showsyouthekernel'sresponse.

Inotherwords,theshellistheUnixFinder.It's

theprogramthatletsyounavigatethecontents

ofyourharddrive,seewhat'sinsidecertain

folders,launchprogramsanddocuments,andso

on.

Thereareactuallyseveraldifferentshells

availableinUnix,eachwithslightlydifferent

commandsyntax.Allofthepopularones—like

tcsh,ksh,andzsh—comewithMacOSX.(You

canchooseamongthemasyourdefaultshell

using,ofallthings,theAccountspaneofSystem

Preferences.Clickthe



,enteryour



Administratorpasssword,andthenControl-click

orright-clickyouraccountnameinthelist;

chooseAdvancedOptions.There,onthe

AdvancedOptionspanel,you'llfindtheLogin

Shellbox,whereyoucanmakethechange.)But

onacleaninstallationofLeopard,Terminal

comessettousebash.

bashevolvedfromtheoriginalshshell,which

wasnamedtheBourneshellafteritsinventor.

bashgotitsname,then,astheBourneAgain

Shell(getit?).

YoucanopenadditionalTerminalwindows(100

ormore,dependingonhowmanyother

programsarerunning)bychoosingFile New

ShellWindow.Evenslicker,Leopard'sTerminal

nowletsyouopenmultiplesessionsintabs(just

likewithSafari)bychoosingFile NewTab.Each

windowandtabrunsindependentlyofany

others.Forproof,tryopeningseveralwindows

andthenrunningthecalcommandineach.



Trythisone:Typecalattheprompt,andthenpressEnter.Unix

promptlyspitsoutacalendarofthecurrentmonth.



















office-mac:~chris$cal

May2008

SuMoTuWeThFrSa

123

45678910

11121314151617

18192021222324

25262728293031







office-mac:~chris$



Thistime,trytypingcal62008,cal-y,orcal-yj.Thesethree

commandsmakeUnixgenerateacalendarofJune2008,a

calendarofthecurrentyear,andacalendarofJuliandaysof

thecurrentyear,respectively.

Tip:Themouseisn'tveryusefulatthecommandline.You

generallymovethecursoronlywiththeleftandrightarrow

keys.(TheDeletekeyworksasitalwaysdoes.)Youcanusethe

mouse,however,toselecttextfromanywhereinthewindow

(orotherprograms)andpasteitinattheprompt.Youcanalso

usethemousetodraganiconoffyourdesktopintothe

Terminalwindow,asshowninFigure16-3.



Chapter16.TheUnixCrashCourse

Asyou'recertainlyawarebynow,MacOSX'sresemblanceto

theoriginalMacoperatingsystemisonlysuperficial.Theengine

underneaththeprettyskinisutterlydifferent.Infact,it'sUnix,

oneoftheoldestandmostrespectedoperatingsystemsinuse

today.Thefirsttimeyouseeit,you'dswearthatUnixhasabout

asmuchincommonwiththeoriginalMacOSasaJeepdoes

withamelon(seeFigure16-1).

WhattheillustrationatthebottomofFigure16-1shows,of

course,isacommandlineinterface:aplacewhereyoucan

typeoutinstructionstothecomputer.Thisisaworldwithout

icons,menus,ordialogboxes.Themouseisalmostuseless

here.

Surelyyoucanappreciatetheirony:Thebrillianceofthe

original1984Macintoshwasthatiteliminatedthecommand

lineinterfacethatwasstilltherulingpartyonthecomputersof

theday(likeAppleIIandDOSmachines).Mostnongeeks

sighedwithrelief,delightedthatthey'dneverhavetomemorize

commandsagain.Yethere'sMacOSX,Apple'ssupposedly

ultramodernoperatingsystem,completewithacommandline!

What'sgoingon?

Actually,thecommandlineneverwentaway.Atuniversities

andcorporationsworldwide,professionalcomputernerdskept

rightonpoundingawayatthelittleC:or$prompts,

appreciatingtheefficiencyandpowersuchdirectcomputer

controlaffordedthem.

You'reforgivenifyourreactiontotheideaoflearningUnixis,

"Forgoodness'sake—can'tIfinishlearningonewaytocontrol

mynewoperatingsystembeforeIhavetolearnyetanother

one?"

Absolutely.YouneverhavetouseMacOSX'scommandline.In

fact,Applehassweptitfarundertherug,obviouslyexpecting

thatmostpeoplewillusethebeautifuliconsandmenusofthe



regulardesktop.Thereare,however,sometasksyoucan

performonlyatthecommandline,althoughfewerwitheach

releaseofMacOSX.

Figure16-1.Top:Whatmostpeoplethinkofwhenthey

think"Macintosh"isagraphicinterface(GUI)—onethat

youcontrolwithamouse,usingiconsandmenusto

representfilesandcommands.

Bottom:TerminaloffersasecondwaytocontrolMacOS

X:acommandlineinterface,whichyouoperatebytyping

outprogrammingcommands.



ForintermediateoradvancedMacfanswithalittletimeand

curiosity,however,thecommandlineopensupaworldof

possibilities.ItletsyouaccesscornersofMacOSXthatyou

can'tgettofromtheregulardesktop.Itletsyouperform

certaintaskswithmuchgreaterspeedandefficiencythanyou'd

getbyclickingbuttonsanddraggingicons.Anditgivesyoua

fascinatingglimpseintothemindsandmoodsofpeoplewho

liveandbreathecomputers.

Ifyou'veeverdabbledinExcelmacros,experimentedwith

AppleScript,orsetupaMaconanetwork,youalreadyknow

thetechnicallevelofthematerialyou'reabouttoread.The

Unixcommandlinemaybeunfamiliar,butitdoesn'thavetobe



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

Chapter 16. The Unix Crash Course

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

×