Tải bản đầy đủ - 0 (trang)
Chapter 30. The Use of History

Chapter 30. The Use of History

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

.cshrc(or.tcshrc)file,wherenisthenumberofpastcommandsthatyouwantto

save:



sethistory=n

Inkshandbash,thevariableisHISTSIZE,andit'salreadysetforyou;the

defaultvaluesare128and500,respectively.

Thehistorycommand(Section30.7)liststhesavedcommands,eachwithan

identifyingnumber.(It'salsopossibletoconfiguretheshellstoprintthehistory

numberofeachcommandaspartofyourprompt(Section4.3).)

Intcsh,csh,andbash,youcanrepeatapastcommandbytypingitsnumber(or

itsname)precededbyanexclamationpoint(!).Youcanalsoselectonlypartsof

thecommandtoberepeatedandusevariouseditingoperatorstomodifyit.

Section30.8andSection28.5givequicktutorialsummariesofsomeofthe

wonderfulthingsyoucando.Mostoftherestofthechaptergivesamiscellany

oftipsforusingandabusingtheshells'historymechanism.

Mostshells—excepttheoriginalBourneandCshells—alsohaveinteractive

command-lineediting(Section30.14).Interactiveeditingmightseemtobe

betterthantyping!viorlpr!$.Ifyoulearnbothsystems,though,you'll

findplentyofcaseswherethe!systemisfasterandmoreusefulthaninteractive

editing.

—TOR



30.2HistoryinaNutshell

SummaryBox

TheCshellandbashcansavecopiesofthepreviouscommandlinesyoutype.

Later,youcanaskforacopyofsomeorallofapreviouscommandline.That

cansavetimeandretyping.

Thisfeatureiscalledhistorysubstitution,andit'sdonewhenyoutypeastring



thatstartswithanexclamationpoint(!command).Youcanthinkofitlike

variablesubstitution($varname)(Section35.9)orcommandsubstitution

('command')(Section28.14):theshellreplaceswhatyoutype(like!$)with

somethingelse(inthiscase,partorallofapreviouscommandline).

Section30.1isanintroductiontoshellhistory.Thesearticlesshowlotsofways

tousehistorysubstitution:

Westartwithfavoriteusesfromseveralcontributors—Section30.3,

Section30.4,Section30.5,andSection30.6.

Section30.8startswithaquickintroduction,thencoversthefullrangeof

historysubstitutionswithaseriesofexamplesthatshowthedifferent

kindsofthingsyoucandowithhistory.

(BackinSection28.5areexamplesofcsh/tcshandbashoperatorssuchas

:r.Manyofthesecanbeusedtoedithistorysubstitutions.)

Seeaneasywaytorepeatasetofcsh/tcshorbashcommandsinSection

30.9.

Eachshellsavesitsownhistory.Topassashell'shistorytoanothershell,

seeSection30.12andSection30.13.

Youdon'thavetouseanexclamationpoint(!)forhistory.Section30.15

showshowtousesomeothercharacter.

TheKornshelldoeshistoryinadifferentway.Section30.14introduces

partofthat:command-lineeditinginkshandbash.

Onelastnote:puttingthehistorynumberinyourprompt(Section4.3)

makesiteasytoreusecommandsthathaven'tscrolledoffyourscreen.

—JP



30.3MyFavoriteIs!$

Iuse!$somuchthatit'salmostasinglecharactertome.Itmeans"takethelast

thingonthepreviouscommandline."SincemostUnixcommandshavethe

filenamelast,youoftenneedtotypefilenamesonlyonce,andthenyoucanuse



!$insubsequentlines.Herearesomeexamplesofwhereitcomesinhandy:

Igetalotoftararchives(Section39.2).Toextractandeditafilefrom

them,Ifirstmakeabackupforeasycomparisonafterediting:



%tarxzfprog.1.05.tar.gzfoo.c

%cp-i!$!$.orig

cp-ifoo.cfoo.c.orig

Thesametrickisalsogoodwhenyou'veeditedafilewithviandthenwant

tocheckitsspelling:



%vifred.letter.txt

%ispell!$

Youoftenwanttomoveafiletoanotherdirectoryandthencdtothat

directory.The!$sequencecanalsobeusedtorefertoadirectory:



%mvgrmacs.tar/usr/lib/tmac

%cd!$

cd/usr/lib/tmac

—AN



30.4MyFavoriteIs!:n*

Iuse!$(Section30.3)alot,butmyfavoritehistorysubstitutionis!:n*,where

nisanumberfrom0to9.Itmeans"takeargumentsnthroughthelastargument

onthepreviouscommandline."SinceItendtousemorethanoneargumentwith

Unixcommands,thisletsmetypethearguments(usuallyfilenames)onlyonce.

Forexample,touseRCS(Section39.5)andmakeanedittoarticlefilesnamed

Section35.5andSection29.2forthisbook,Idid:



%co-l1171.sgm6830.sgm2340.sgm

RCS/1171.sgm,v->1171.sgm



...

RCS/2340.sgm,v->2340.sgm

revision1.8(locked)

done

%vi!:2*

vi1171.sgm6830.sgm2340.sgm

3filestoedit

...

%ci-m"ChangedTERMxref."!*

ci-m"ChangedTERMxref."1171.sgm6830.sgm2340.sgm

...

Inthefirstcommandline(co),Itypedthefilenamesasarguments2,3,and4.In

thesecondcommandline(vi),Iused!:2*;whichgrabbedarguments2

throughthelast(inthiscase,argument4)fromthefirstcommandline.The

resultwasasecondcommandlinethathadthosethreefilenamesasits

arguments1,2,and3.So,inthethirdcommandline(ci),Iused!*topick

arguments1throughthelastfromtheprevious(second)commandline.(!*is

shorthandfor!:1*.)

Youcanalsograbargumentsfrompreviouscommandlines.Forexample,

!em:2*grabsthesecondthroughlastargumentsonthepreviousemacs

commandline(commandlinestartingwith"em").Therearelotsmoreofthese

inSection30.8.

Iftheseexampleslookcomplicated,theywon'tbeforlong.Justlearntocountto

thefirstargumentyouwanttograb.Ittookmeyearstostartusingthese

substitutions—butthey'vesavedmesomuchtypingthatI'msorryIdidn'tget

startedearlier!

—JP



30.5MyFavoriteIs^^

Well,maybeit'snotmyfavorite,butit'sprobablythehistorysubstitutionIuse



mostoften.It'sespeciallyhandyifyouhavefumble-fingersonastrange

keyboard:



%catmyflie

cat:myflie:Nosuchfileordirectory

%^li^il

catmyfile

Obviously,thisdoesn'tsavemuchtypingforashortcommand,butitcansurebe

handywithalongone.Ialsouse^^with:p(Section30.11)torecallanearlier

commandsoIcanchangeit.Forexample:



%!m:p

moregobbledygook.c

%^k^k2

moregobbledygook2.c

Thepointissometimesnottosavetyping,buttosavetheeffortofremembering,

suchas,IwanttoprintthefileIlookedatearlier,butdon'tremembertheexact

name.

[MykeyboardcanrepeatcharacterswhenI'mnotexpectingit.Iuseasingle^to

deleteextracharacters.Forexample:



%lprsources/aproggg.c

lpr:sources/aproggg.c:nosuchfileordirectory

%^gg

lprsources/aprog.c

Youcouldtype^gg^,butthesecondcaretisn'trequired.Withasinglecaret,

youdon'ttypeareplacementstring—justthestringtodelete.—JP]

—TOR



30.6Using!$forSafetywithWildcards



Weallknowaboutusinglsbeforeawildcardedrmtomakesurethatwe'reonly

deletingwhatwewant.Butthatdoesn'treallysolvetheproblem:youcantype

lsa*andthenmistakenlytyperms*withbadconsequences—it'sjusta

minorslipofyourfinger.Butwhatwillalwaysworkis:



%lsa*

a1a2a3

%rm!$

(ls-da*(Section8.5)willmakelessoutputifanysubdirectorynamesmatchthe

wildcard.)

Usingthehistorymechanismtograbthepreviouscommand'sargumentsisa

goodwaytopreventmistakes.

—ML



30.7HistorybyNumber

Mostofthehistoryexampleswe'veshownusethefirstfewlettersina

command'sname:!emtorepeatthepreviousEmacscommand,forexample.

Butyoualsocanrecallpreviouscommandsbytheirnumberedpositioninthe

historylist.That'susefulwhenyouhaveseveralcommandlinesthatstartwith

thesamecommand.It'salsomoreusefulthaninteractivecommand-line

editing(Section30.14)whenyou'dliketoseealotofpreviouscommandsat

onceandthenchooseoneofthembynumber.

Tolistpreviouscommands,usethehistorycommand.Forinstance,inbashand

theCshells,history20showsyourlast20commands.InzshandtheKornshell,

useahyphenbeforethenumber:history-20(alsoseethediscussionoffc,later

inthisarticle).Here'sanexample:



$history8

15showlast+upt/authors

16vi../todo

17co-l0444.sgm



18vi0444.sgm

19ci-u0444.sgm

20rcsdiff-u3.40444.sgm>/tmp/0444-diff.txt

21scp/tmp/0444-diff.txtwebhost:adir/11.03-diff.txt

22getmail;ndown

$rm!20:$

rm/tmp/0444-diff.txt

$!16

vi../todo

Thenumberatthestartofeachlineisthehistorynumber.So,toremovethe

temporaryfileIcreatedincommand20(thenameofwhichI'dalready

forgotten!),Icanuse!20:$(Section30.8)topassthatfilenameasanargumentto

rm.Andtorepeatcommand16(vi../todo),Icantype!16.

Thissortofthingisoftenfasterthanusingarrowkeysandeditorcommandsto

recallandeditpreviouscommands.Itletsmeseeseveralcommandsallatonce,

whichmakesiteasiertospottheone(s)IwantandtorememberwhatIwas

doingasIworked.IuseitsooftenthatI'vegotasetofaliasesthatlistbigger

andbiggerchunksofpreviouscommandsandanaliasthatsearcheshistory,

givingmeachunkofmatchingcommandlines.HeretheyareinCshellsyntax:



lessSection12.3,\!*Section29.3



aliashhistory5#showlastfivelines

aliashihistory10#showlasttenlines

aliashishistory20#showlast20lines

aliashist'history40|less'#showlast40;

aliashisto'history70|less'#showlast70;

aliasH'history-r|fgrep"\!*"'#findsomething

Thehistory-roptionshowsthelistinreverseorder:mostrecentfirst.Ifyou

don'tgiveacountoflinestolist,you'llseeallofthem.

Becareful!Inbash,history-rreadsthecurrenthistoryfileandusesit



asthehistoryfromthatpointonward,trashinganycurrenthistoryfor

thatshellifithasnotyetbeenwrittentothehistoryfile(definedin

theenvironmentvariableHISTFILE).



Toavoidtypingthehistorycommand,youcanincludethehistorynumberin

yourprompt(Section4.3).Thenyoucanrepeatarecentcommandbyglancing

upyourscreentofindthecommandnumberfromitsprompt.

There'sanotherwaytoseealistofyourpreviouscommandsinbash,ksh,and

zsh:thecommandfc-l(lowercaseL,for"list").(Inksh,thecommandhistoryis

actuallyjustanaliasthatexecutesfc-l.)Byitself,fc-lliststheprevious16

commands:



$fc-l

...

19ls-F

20lessexpn.c

21viexpn.c

22make

23expninfo@oreilly.com

24fc-l

Foranevenshorterlist,givefcthefirstnumberornameyouwanttolist.For

instance,fc-lviorfc-l21wouldgivethelastfourlinesabove.

Youcanalsouseasecondargumentthatendstherangebeforethecurrentline.If

youtypefc-lviexpnorfc-l2123,you'llseecommands21

through23.

tcshandzshautomaticallykeeptimestampswiththeirhistory.Thetcsh

commandhistoryshowsthetimeofdaybydefault.Inzsh,youcanseethisinfo

withtheoptions-d,whichshowsthetimes,-f,whichshowsbothdatesand

times,and-D,whichshowselapsedtimes.Forexample,thescpcommand

startedrunningat12:23(PM)andtook1minute29secondstorun:



%fc-l-f-4

100310/23/200012:23nup



100410/23/200012:23scp../upt3_changes.htmlwebho

100510/23/200012:25less/etc/hosts

100610/23/200012:25getmail;ndown

%fc-l-D-5

10030:29nup

10041:29scp../upt3_changes.htmlwebhost:adir/.

10050:05less/etc/hosts

10060:21getmail;ndown

10070:00fc-l-f-4

zshalsohasseveralrelatedoptionsforfcthatallowforthehistorytobewritten

outtoafile,readinfromafile,etcetera.Theothershellsallowforevenmore

extendedfunctionality.Inbash,forexample,fc-ewithappropriateoptionswill

startaneditor(definedbytheFCEDITenvironmentvariable)andloadupanew

filecontainingtherecenthistoryitems.Thinkofitisjumpstartingascriptfrom

asequenceof(hopefully)successfullyexecutedcommands.Seetheothershells'

manualpagesformoredetails.

—JPandSJC



30.8HistorySubstitutions

Althoughmostoftheexampleshereuseechotodemonstrateclearlyjustwhatis

goingon,you'llnormallyusehistorywithotherUnixcommands.

Theexclamationpoint(!)isthedefault(Section30.15)historysubstitution

character.Thisallowsyoutorecallpreviouslyenteredcommandsandre-execute

themwithoutretyping.Tousethe!inacommandline,youhaveseveral

choices.Someofthefollowingexamplesaremoreofaheadachethantheymay

beworth,buttheyarealsousedtoselectargumentsfromthecommandlinein

aliases(Section29.3):



!!repeatsthelastcommand.

!:repeatsthelastcommand.Thisformisusedifyouwanttoadda



modifier(Section28.5)likethefollowing:



%echoxy

xy

%!:s/xy/yx

echoyx

yx

Thesecond!wasleftout.



!sorepeatsthelastcommandthatstartswithso.

!?fn?repeatsthelastcommandthathasfnanywhereinit.Thestring

couldbefoundinanargumentorinthecommandname.Thisisopposedto

!fn,inwhich!fnmustbeinacommandname.(Thelast?neednotbe

there.Thus!?fnmeansthesamething.)



!34executescommandnumber34.Youcanfindtheappropriatehistory

numberwhenyoulistyourhistoryusingthehistorycommand,orby

puttingthehistorynumberinyourprompt(Section4.3).



!!&addsanampersand(&)totheendofthelastcommand,which

executesitandplacesitintothebackground.Youcanaddanythingtothe

endofapreviouscommand.Forexample:



%cat-vfoo

...

%!!|more

cat-vfoo|more

...

Inthiscasetheshellwillrepeatthecommandtobeexecutedandrunit,

addingthepipethroughthemorepager.Anothercommonusageis:



%cat-vfoo



...

%!!>out

cat-vfoo>out

whichreturnsthecommandbutredirectstheoutputintoafile.



!:0selectsonlythecommandname,ratherthantheentirecommandline.

%/usr/bin/grepAhfn1

...

%!:0Bhfn2

/usr/bin/grepBhfn2

Notethatasanoperator(Section28.5,),:0canbeappendedtothese

historysubstitutionsaswell.Forexample,!!:0willgivethelast

commandname,andacolonfollowedbyanynumberwillgivethe

correspondingargument.Forexample,!:3givesthethirdargument:



%catfnfn1fn2

...

%more!:3

morefn2

...

!:2-4givesthesecondthroughthefourthargument;useanynumbers

youchoose:



%echo12345

12345

%echo!:2-4

echo234

234

!:-3giveszerothroughthethirdargument;useanynumberyouwish:



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

Chapter 30. The Use of History

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

×