Вы находитесь на странице: 1из 22

5/20/2015

WindowsShellTutorial

WindowsShellTutorial
CayS.Horstmann

WindowsShellTutorialbyCayHorstmannislicensedunderaCreativeCommonsAttributionNoncommercialShare
Alike3.0UnitedStatesLicense.

OperatingSystems,UserInterfaces,andShells
Theoperatingsystemmanagestheresourcesofacomputer,suchasitsinternalmemory,thediskdrives,keyboard,
monitorscreen,mouse,printers,andnetworkconnections.Peoplewhouseacomputertobrowsetheweborplaygames
haveminimalcontactwiththeoperatingsystem.Mostoftheirtimeisspentwithapplicationprograms.
Theseuserstendtousetheoperatingsystemonlytofixproblems,forexamplewithafailedinternetconnection.Themost
recentversionsofpopularoperatingsystems(suchasWindowsXP)havebecomeverymuchorientedtowardsthe
consumer,hidingallbutthemostbasictasksfromthecasualuser.
Computerprogrammershavemoreadvancedneedsthanpeoplewhousethecomputerasatool.Programmersneedto
compileandlaunchprogramsandautomaterecurringtasks.Thistutorialiswrittenforprogrammerswhoarealready
familiarwiththebasicsofusingacomputer.
Ifyouhavepriorexperienceusingacomputerforplayinggamesorwritingreportsandarenowlearningtoprogram,you
willneedtolearnmoreaboutyouroperatingsystem.Somestudentsarereluctanttoembarkonthiseffort,eitherbecause
theyfeelthattheyalreadyknowhowtousetheircomputer,orbecausetheyalreadyhavetheirhandsfulllearningabout
programming.However,thatisashortsightedattitude.Withoutknowingtheoperatingsystem,manycommon
programmingtasksseemtediousorevenimpossible.
Operatingsystemscomewithtwodifferentkindsofuserinterface:
agraphicaluserinterfaceorGUI
acommandlineinterface,alsocalledashell
MostcomputerusersarefamiliarwiththegraphicaluserinterfaceorGUI.MostGUIenvironmentsdisplayadesktopthat
ispopulatedwithwindows,iconsandmenus.Youuseapointer(directedbyamouseortrackball)toselectitemsonthe
desktop.TheseinterfacesaresometimescalledWIMPinterfaces,afterthefirstlettersofthewordswindow,icon,menu,
andpointer.HereisascreencaptureofatypicalWIMPinterface:

http://www.horstmann.com/bigj/help/windows/tutorial.html

1/22

5/20/2015

WindowsShellTutorial

Theotheruserinterfaceisacommandshell.Acommandshellissimplyawindowwithoutanygraphicaldecorations.You
typecommands,usingthekeyboard,andyouseetheresultsofthecommandsdisplayedastext.Therearenoicons,and
youcanusethemouseonlyinlimitedcircumstances.Hereisatypicalcommandshell:

Acommandshellisnotagooduserinterfaceforcasualusers.However,experiencedusersfindthatthecommandshellis
indispensibleformanytasks.
Lookatitthisway.Ifyoujustwanttosnapvacationphotos,you'llusea"pointandshoot"camera.Itrequiresnotraining
andtakesdecentpictures.

http://www.horstmann.com/bigj/help/windows/tutorial.html

2/22

5/20/2015

WindowsShellTutorial

Butifyouwantyourphotostobepublishedinamagazine,youwillneedaprofessionalcamera.Youwillneedtospend
timelearningrathertechnicalconceptssuchasfstopsandshutterspeeds.

Wedon'twanttoleaveyouwiththeimpressionthatthecommandshellisthebesttoolforeveryjob.Sometimes,youare
betteroffusingtheGUI,particularlyifyouspendsomeeffortlearninghowtouseitefficiently.Justlikeaprofessional
photographerchoosesthebestinstrumentforthejob,youwillneedtolearnwhentousetheGUIandwhentousethe
commandshell.
Inthistutorial,youwilllearnsometricksthatmaketheGUIfasterandmoreefficient,andyouwilllearnthebasicsofthe
commandshell.

KeyboardShortcuts
Runningaprogram
Afteryoulogontoyourcomputer,youseeadesktop,whichmayormaynotcontainsomeicons(smallpictures
representingprograms,services,orresources).AtthebottomleftofthescreenistheStartbutton.Acrossthebottom,isthe
taskbarwhichcontainsbuttonsforallcurrentlyrunningprograms.Ifyouarereadingthisdocumentinawebbrowser
(andnotfromaprintout),thenthereshouldbeabuttoncorrespondingtothebrowserprogram.Atthebottomrightofthe
screenisaclock,possiblytogetherwithsomesmallericons.
Youprobablyknowhowtolaunchprogramsbyclickingonthestartbuttonorondesktopicons.Wewillnowintroduce
anothermethod.
TypethekeyboardshortcutCtrl+Esc.Thatis,holddowntheCtrlkey,and,withoutliftingyourfingeroffit,holddown
theEsckey.Thenletgoofbothkeys(ineitherorder).ThiskeyboardshortcutsimulatesaclickontheStartbutton.
Whyuseakeyboardshortcut?ItismuchfastertohitCtrl+Escthanitisto
1. grabthemouse
2. movethemousetothelowerleftcornerofthescreen
3. clickthemousebutton
Foraprogrammer,thefirststep("grabthemouse")isthemostpainful.Programmersneedtotypealotofcodeand
thereforehavetheirhandsonthekeyboardmostofthetime.Inthisregard,programmersareverydifferentfromcasual
computeruserswhohaveahandonthemousemuchofthetime.
Youwillseeapopupmenu,containingiconsandnames.Theexactlayoutofthemenudependsontheversionof
Windowsandonthecustomizationofthestartmenu.Hereisoneexample.Yourdialogmaywellbequitedifferent.

http://www.horstmann.com/bigj/help/windows/tutorial.html

3/22

5/20/2015

WindowsShellTutorial

NOTE:IfyouuseWindowsXP,itisagoodideatoswitchthestartmenuto"Classic"mode.Thesettingis
insidetheTaskbarandStartMenucontrolpanel.(Whileyouareatit,youshouldswitchthecontrolpanel
viewto"Classic"modeaswell.)

Inanymenu,youcanquicklyselectitemsthathaveunderlinedlettersintheirnames.Forexample,typingRisthesameas
selectingtheRunitem.TypingHisthesameasselectingtheHelpitem.

NOTE:IfyouuseWindowsXP,theunderlinedlettersmaynotshowupuntilyouhittheAltbutton.This
unfortunatebehaviorcanbecorrectedintheDisplayPropertiescontrolpaneldialog.SelecttheAppearance
tabandclickontheEffectsbutton...
HittheRkeynow.Youwillgetadialog.Typethewordnotepad.
Inmostdialogboxes,hittingtheEnterkeyisthesameasclickingtheOkbutton.TypingEscdismissesthedialog,justas
ifyouhadclickedtheCancelbutton.
HittheEnterkeynow.TheNotepadprogramlaunches.

Exercise1
WhichkeystrokesarerequiredtolaunchtheNotepadprogramwithouttouchingthemouse?
Exercise2
WhatistheadvantageofusingtheRundialogtolaunchtheNotepadprogram?Hint:LocatetheNotepadprograminthe
startmenutree.Inwhichsubmenudidyoufindit?Howlongdidittakeyoutofindit?Willitbeinthesamepositionon
yourfriend'scomputer?

Togglingbetweenprograms
Thenextstepofthistutorialassumesthatyoucurrentlyhaveawebbrowserrunning.Ifyouarereadingtheseinstructions
fromaprintout,goaheadandstartabrowser.Closeanywindowsexceptforthebrowserandthenotepadwindow.
Younowhavetwowindowsonyourdesktop:thebrowserandtheNotepadprogram.Thisisanextremelycommon
http://www.horstmann.com/bigj/help/windows/tutorial.html

4/22

5/20/2015

WindowsShellTutorial

situationforaprogrammer.Youwilloftenwriteaprograminonewindowwhileconsultingdocumentationinanother
window.Itisessentialthatyoucanswitchquicklybetweenthewindows,evenifsomewindowshideothers.
ThefastestwayofswitchingbetweenwindowsistheAlt+Tabkeyboardshortcut.PressAlt+Tabnow.Youwillgeta
dialogthatlistsallwindows.Releasebothkeys.Youinstantlyswitchtothenextwindow.
Startthecalcprogram(Ctrl+EscRcalcEnter).Youshouldnowhavethreeprogramsrunning.HitAlt+Tabagain,but
thistimekeeptheAltkeydepressedandrepeatedlyhittheTabkey.Youtogglethroughtheprogramicons.Letgoofboth
keyswhenyouhavereachedthebrowserprogram.
Exercise3
Runthreeprograms,forexample,abrowser,thenotepad,andthecalcprogram.Switchtothebrowserprogramifitisnot
currentlyactive(eitherwiththemouseorwithAlt+Tab).HitAlt+Tabandletgoimmediately.Whichprogramis
selectednow?HitAlt+Tabagainandletgoimmediately.Whichprogramisselectednow?Whyistheresultsurprising?
Whyisituseful?

Managingwindows
Whenthetimehascometocloseanunwantedwindow,youcancloseitbyclickingontheXiconinthetoprightcorner,or
youcanuseakeyboardshortcut.Thereareactuallytwoshortcuts.ThecombinationAlt+F4closestheactivewindow,but
evenkeyboardenthusiastswillfindithardtoremember.
MoreusefulistheAlt+Spaceshortcut.Itbringsupthewindowmenu:

SelectCtoclosethewindow.
Thewindowmenuhasanumberofotherusefuloptions:
Maximize:Makethewindowfilltheentiredesktop
Restore:Restorethewindowtoitsoriginalsize,beforemaximizing
Minimize:Temporarilyremovethewindowfromthescreen(toreduceclutter)
YoucangetaminimizedwindowbackontothedesktopbycyclingtoitwithAlt+Tab.
Exercise4
Supposeyouwanttoseeasmuchinformationaspossibleinyourbrowserwindow.Whatkeystrokesdoyouuseto
maximizethebrowserwindow?

Cut,CopyandPaste
Oneofthemostcommonoperationsfortextmanipulationiscutandpaste:transferringinformationfromoneplaceto
another.Becausetheseoperationsaresocommon,therearespecialkeyboardshortcutsforthem.
Switchtothenotepadwindow.
PulldowntheEditmenubytypingAlt+E.NotetheunderlinedEinthemenuname.Youpulldownamenubytypingthe
Altkeyandtheunderlinedletter.

http://www.horstmann.com/bigj/help/windows/tutorial.html

5/22

5/20/2015

WindowsShellTutorial

TheEditmenuhascommandsfortheCut,Copy,andPasteoperations.Thus,aperfectlyreasonablekeyboardshortcutfor
copyingtextwouldbeAlt+EC.However,becausethecopyoperationissocommon,thereisanaccelerator,Ctrl+C,that
letsyouaccesstheoperationwithasinglekeycombination.Youcanseetheacceleratorlistedinthemenu.Similarly,there
areacceleratorsforcut(CtrlX)andpaste(CtrlV).Thesekeycombinationsareperhapsnotaseasytoremember.You
mayfindithelpfultovisualizetheXascrossingouttext,andtheVasaninsertmarkforaddingtext:

AlsonotethatthelettersX,C,Varelocatednexttoeachother,convenientlyclosetotheCtrlkey(atleast,onthestandard
EnglishQWERTYkeyboardlayout).

Exercise5
Nowswitchtothebrowserwindow.Ifitdoesn'tcurrentlyshowadocument,thenvisityourfavoritewebsite.Usethe
mousetoselectaphraseofyourchoice.YourtaskistocopytheselectedtexttotheNotepadprogram,withoutfurther
useofthemouse.Whatkeystrokestoyouuse?
NOTE:Manyprogramsalsosupportalternatekeyboardshortcuts:Shift+Deleteforcut,CtrlInsertforcopy,
andShiftInsertforpaste.However,theseshortcutsarenotasuniversallysupportedasCtrlX,CtrlC,
CtrlV.

MovingtheCursorandSelectingText
Youcanmovethecursorbyclickingonthedesiredlocation,andyoushoulddothatifthedesiredlocationisfarfromthe
currentlocation.However,ifyoujustneedtomovethecursorbyasmallamount,itisoftenfastertousethefollowing
keys:
ThearrowkeysLeft,Right,Up,Downmovethecursoroneposition
Ctrl+Left,Ctrl+Rightmovethecursoronewordtotheleftorright
Home,End(abovethearrowkeys)movethecursortothebeginningorendoftheline
PageUp,PageDown(abovethearrowkeys)scrollthepageupordown.Thisisoftenfasterthanusingthescroll
bars.

http://www.horstmann.com/bigj/help/windows/tutorial.html

6/22

5/20/2015

WindowsShellTutorial

Youknowthatyoucanselecttextwiththemouse,byclickingonthebeginningofthetextanddraggingthemousetothe
end.Indeed,thatisoftenthefastestmethod.However,ifyouneedtoselectashortamountoftextandyourfingersareon
thekeyboard,thenitisusefultoknowashortcut.
HolddowntheShiftkeyandmovethearrowkeys.Youwillseethataportionoftextisselected.Youcanalsousekeys
suchasHomeandEndtoextendtheselectiontothebeginningandtheendofaline.
Exercise6
Switchtothenotepad.Itshouldstillcontainsometextfromaprecedingexercise.Ifnot,pasteortypeacoupleoflines.
Nowhighlighttheentirelinecontainingthecursor,usingasfewkeystrokesaspossible.Whatkeystrokestoyouuse?

NavigatinginDialogs
Itishandytoknowhowtomovequicklythroughthefieldsofadialogboxwithoutusingthemouse.
Inanydialogbox,youcanusetheTabkeytocyclethroughallofthefieldsandbuttons.Considerforexamplethe
followingdialogfromtheNotepadprogram.(ThemenuoptionisEdit>Replace.)

NOTE:ThisisthedialogfromWindowsXP.IfyouuseanolderversionofWindows,usetheSearch>
Finddialoginstead.Itisn'tasinteresting,butyoucanstilluseittotryouttheTabkeybehavior.
TypetheFindwhatentry,thenhittheTabkeytoquicklygettotheReplacewithfield.TheTabkeyisparticularlyhandy
fordialogsthathavemanytextfields.
WhenyouusetheTabkeytocyclethroughthedialogbox,observehowthefocusshiftsfromonefieldtothenext.Atext
fieldwithfocushasablinkingcursor.Abuttonwithfocushasadottedrectanglearoundthebuttonlabel.Thefocustells
youwhichpartofthedialogboxreceiveskeyboardinput.Forexample,ifabuttonorcheckboxhasfocus,thenhittingthe
Spacebaristhesameasclickingitwiththemouse.
http://www.horstmann.com/bigj/help/windows/tutorial.html

7/22

5/20/2015

WindowsShellTutorial

Ifanitemnamehasanunderlinedletter(suchasMatchcase),thenyoucantypeAlttogetherwiththeunderlinedletterto
reachitquickly.Forexample,Alt+CisthesameasclickingtheMatchcasecheckbox.
Finally,mostdialogsrespondtotwospecialkeys.TypingEscdismissesthedialog,justasifyouhadclickedtheCancel
button.TypingEnteristhesameasclickingtheOkbutton.
Exercise7
OpenuptheFinddialoginNotepad.WhatkeystrokesdoyouneedtofindthenextoccurrenceofHello,withMatchcase
checked?Keystrokesonly,nomouse!

Youknowknowthemostcommonkeyboardshortcuts.Afterashortamountofpractice,youwillprobablyagreethatthe
keyboardismightierthanthemouseformanyroutinetasks.

TheFileSystem
Diskdrives
Diskdrivesforcomputerscomeintwomaintypes,removable(floppy,CDROM)andnonremovable(hard).Whetherhard
orfloppy,acomputerdiskdriveessentiallycontainsaround,flat,object,anditreadsitssurfacewithamagneticoroptical
head.
Inadditiontothediskdrivesthatarephysicallypresentinacomputer,theremaybeseveralmappeddrivesthatare
providedbythenetworkserver.Thesearenotactualdrivesatall,butlooktotheoperatingsystem(andtoyou)asthough
theyare.
Thedrivesthatholdthedisksarenamedbyaletterfollowedbyacolon(:).Thenamesa:(andperhapsb:)arethefloppy
drives.Thenamesc:andd:areusuallyusedtonameharddiskdrivesinthatsamecomputer.CDROMScomenext,
labelede:(ord:ifthereisonlyoneharddisk).Higherletterslikej:,k:,...aremappednetworkdrives.
NOTE:Sometimes,asingleharddrivehasmultiplepartitions.Eventhoughthereisonlyasinglephysical
drive,itdividedintoseveralareas,eachofwhichhasitsowndriveletter(c:,d:,...).Ifyousetupyourown
computer,itisanexcellentideatosetuptwopartitions,onefortheoperatingsystem(c:)andoneforyour
personaldata(d:).Thatsetupenablesyoutoreinstalltheoperatingsystemwithoutinterferingwithyour
personaldata.(Unfortunately,theWindowsoperatingsystemisnotoriousforbecomingunreliableovertime,
asmoresoftwareisinstalledandprogramsanddriversinterferewitheachother.Thebestremedyisto
periodicallywipethec:partitioncleanandreinstallWindows.)

NOTE:InLinux/Unix/MacOSX,therearenodriveletters.Instead,CDROMandfloppydrivesareaccessed
throughpathssuchas/mnt/cdromand/mnt/floppy.

TherearemanywaystofinddrivesandviewtheircontentsusingWindows.TheprogramwewilluseiscalledWindows
Explorer.(ThisisnotthesameprogramasInternetExplorer,Microsoft'swebbrowser.TheWindowsExplorerprogram
exploresthefilesystem,nottheinternet.)
TostarttheExplorerprogram,opentheRundialog(Ctrl+Esc,R)andtypeexplorerfollowedbytheEnterkey.

http://www.horstmann.com/bigj/help/windows/tutorial.html

8/22

5/20/2015

WindowsShellTutorial

ThelookoftheExplorerhaschangedgreatlywithdifferentversionsofWindows,anditcanalsobeconfiguredinmany
ways.Don'tworryifyourExplorerwindowlooksquitedifferentfromthisscreenshot.

Exercise8
Listallavailabledriveswiththeirnamesanddriveletters.(YoumayneedtoopentheMyComputeritem.)

Eachdrivecontainsfilesanddirectories(alsocalledfolders).IntheExplorerprogram,clickonadrivetoseethefilesand
folders.Thefilesaredepictedwithaniconthatlookslikeafilefolder.Fileshavedifferenticonsthatdependontheirtype.

http://www.horstmann.com/bigj/help/windows/tutorial.html

9/22

5/20/2015

WindowsShellTutorial

Exercise9
Listallfilesanddirectoriesthatareinsideyourc:drive.(Don'tlookinsidethedirectories.)

DirectoryTrees
Atypicalharddiskholdsthousandsoffiles.Itisthereforeessentialtoorganizeyourfilesonthedisk.Asyouaccumulate
filesonadisk,youstorethemingroupsbycreatingdirectories.Directoriesarealsocalledfilefolders.Generally,
programmersprefertheterm"directory",andwewillusethatterminthistutorial.
Eachdirectorycancontainanynumberoffilesandotherdirectoriescalledsubdirectories.Thisarrangementisknownasa
hierarchicalortreelikedirectorystructure.
Tovisualizethehierarchyofdirectories,itisbesttolookatthetreeviewtotheleftoftheExplorerwindow.Notethat
eachdrivehasasmallboxnexttoitwitheithera+orsigninit.Thisindicateswhetherthenextlevelofthedirectory
hierarchyishiddenorexpanded.Clickonthe+icontoexpandahiddenlevel,ontheicontohideanexpandedlevel.
Oneachdrive,thehierachystartswiththerootdirectory.Thenameoftherootdirectoryissimplythedrivename
followedbyabackslash(suchasc:\).Therootdirectorycontainsfiles(suchasc:\logfile.txt)anddirectories(suchas
c:\windows).Thewindowsdirectorycontainsotherfiles(suchasc:\windows\notepad.exe)anddirectories(suchas
c:\windows\system).
Thesequenceofsubdirectoriesfromtheroottoagivenfileordirectoryiscalledthepath.Forexample,
c:\windows\systemisthefullpathnameofthesystemdirectoryinsidethewindowsdirectoryinsidethec:drive.
Exercise10
Listanadditionalfileandanadditionaldirectoryinthec:\windowsdirectory.Listafileandadirectoryinthe
c:\windows\system32directory.Givethefullpathnamesforthefilesanddirectories.
Exercise11
http://www.horstmann.com/bigj/help/windows/tutorial.html

10/22

5/20/2015

WindowsShellTutorial

Findthefilesexplorer.exeandtelnet.exe.Givethefullpathnames.(Hint:Youmayfinditeasiertolookforfilesifyou
selectthelistviewratherthantheiconviewfordirectories.ChoosetheView>Listmenuoption.)
Exercise12
Findafilewhosefullpathnamescontainsatleastfourdirectories.
NOTE:InLinux/Unix/MacOSX,directoriesareseparatedbyforwardslashes(/).Forexample,
/usr/local/java/bin.Thatisthesameconventionasforwebpageaddresses.OnlyWindowsusesbackslashes
(\).

MakingDirectories
Forthispartofthetutorial,youneedtofindadirectoryintowhichyouareallowedtoplacefilesandfolders.Onyourown
computer,youcansimplyusec:\,therootdirectoryofthec:drive.Ifyouworkinacomputerlab,youwillneedtofindout
thenameofthedirectorythatwascreatedforyouruse.

ViewyourdirectoryintheExplorerprogram.SelectFile>New>Folder(Alt+FWF).Thiscommandplacesafolder
iconinsidethedirectoryandgivesitthetemporarynameNewFolder.Italsoleavesthecursorinthenamefield,allowing
youtochangeitimmediately.HitDeletetoerasethename,andgiveitanewname.Agoodchoiceforanameisyourown
name,contractedtoasinglewordwithoutspaces(suchasjoeorjqsmith).

Ifyouuseyourowncomputer,createthisdirectorynow.Fromnowon,placeallfilesinthisdirectory.Ifyouusea
computerinalabandsomeoneelsehasalreadygivenyouadirectorywithyourname(perhapsd:\jqsmithor
c:\users\jqsmith),thenyoucanskipthisstep.

Wewillreferto"your"directoryasthec:\yournamedirectoryinthistutorial,eventhoughitwillcertainlybesomething
else(unless,ofcourse,yournameisYolandaO.Urname...)

Exercise13
Createasubdirectorycalledtutorialinsidethec:\yournamedirectory.(Substitutetheactualdirectorythatyoucreated.)
Listallsteps,startingwithlaunchingtheExplorerprogram.(Closeitfirstifitiscurrentlyrunning).

FileandDirectoryNames
Youcanuseletters,numbers,theunderscore(_)andthehyphen()characterinfilenames.Obviously,youcan'tuse
symbolssuchas:and\infilenames,ortheywouldbeconfusedwithdriveanddirectoryseparators.Thereareafewother
specialcharactersthatyoucanuse,butthedetailsdependonwhetherthedriveisalocaldriveoranetworkeddrive.Itis
besttoavoidfilenameswithexoticsymbolssuchas!@#$.

Youcanusespacesinfilenames,butprogrammersrarelydothat,becausespacesinfilenamescreateproblemswhenyou
useacommandshell.Instead,useor_toseparatewords:myprojectver0.01.javaorletter_to_fifi.txt.

Bothuppercaseandlowercaselettersarepermittedinfileanddirectorynames,butWindowswillnotdistinguishbetween
namesthatdifferonlyinthecaseoftheletters.
http://www.horstmann.com/bigj/help/windows/tutorial.html

11/22

5/20/2015

WindowsShellTutorial

Exercise14
CreateanothersubdirectorycalledTUTORIALinsidethec:\yournamedirectory.(Substitutetheactualdirectorythatyou
created.)WhaterrormessagedoesWindowsgiveyou?WhatdoesitdoafteryouclickOK?

Files
StarttheNotepadprogram:Ctrl+EscRnotepadEnter.Typeafewwords.SelectFile>SaveAsfromthemenu.You
willgettheWindowsfiledialog.

Thedialogsuggestsafilename*.txt.However,youcan'tactuallyusethe*characterinafilename.Also,thecurrent
directoryislikelytobewrong.Fortunately,inmostversionsofWindows,theuselessdefaultisalsohighlighted,soyou
canovertypeit.
Simplytypec:\yourname\.(Actually,typethenameofyourpersonaldirectory.)Typethelettersslowlyandpayclose
attentiontotheentryfield.Youwillseethatasmallmenubelowtheentryfieldisfilledwiththenamesthatmatchwhat
youhavetypedatthispoint.

Thisfeatureisagreattimesaver.Assoonasyouseethenamethatmatcheswhatyouwanttotype,hittheDownarrow
buttontoselectit.Presentingallchoicesthatmatchthetypedlettersiscalledincrementalsearch.Clearly,incremental
searchisamarvelousconveniencebecauseitminimizesthenumberofkeystrokes.
Exercise15
Whatchoicesdoyougetafteryoutypetheletterc(orwhateverthedriveletterofyourpersonaldirectoryis)?What
choicesdoyougetafteryoutypec:\andthefirstletterofthedirectoryname?

http://www.horstmann.com/bigj/help/windows/tutorial.html

12/22

5/20/2015

WindowsShellTutorial

NOTE:VeryoldversionsofWindowsdonotofferincrementalsearchinthefiledialog.

Savethefileasc:\yourname\tutorial\sample.txt.Besuretosupplytheextension.txt.Thatextensionsignifiesthatthe
fileisatextdocument.
Exercise16
ClosetheNotepadprogramandlocatethefilethatyoujustsavedintheExplorerprogram.Whaticondoesithave?What
nameisdisplayedforthefile?Whathappenswhenyoudoubleclickonthefilename?
DependingontheconfigurationofWindows,theextension.txtmaynotbedisplayedwhenyouviewthefileinthe
Explorerprogram.Bydefault,Windowshidestheextensions,presumablybecausenaiveusersareconfusedaboutfile
namessuchaslettertoaunttilly.txt.
NOTE:Hidingextensionsisprimarilyhelpfulforviruswriters.ManyWindowsusershaveeagerlydouble
clickedoniconslabeledsomethinglikeprettygirl.gif,onlytolaunchavirusprogramwhoserealnamewas
prettygirl.gif.exe.
Asaprogrammer,youdon'twanttheoperatingsystemtohideinformationfromyou.FireuptheExplorerprogramand
selectTools>FolderOptionsandselecttheViewtab.

akesurethecheckboxnextto"Hidefileextensionsforknownfiletypes"isunchecked.Clickonitifitischecked.Then
hitEnterorclickOK.MakesuretorepeatthissteponeveryWindowscomputerthatyouuse.
Windowsusesthefileextensiontofigureoutwhattodowiththefilewhenyoudoubleclickonit.Doubleclickingona
.txtfilebringsupNotepad.Doubleclickingonaprogramfile(withextension.exe)executestheprogram.
Youcanfindoutwhichprogramcorrespondstoaparticularextension.IntheExplorerprogram,selecttheTools>Folder
http://www.horstmann.com/bigj/help/windows/tutorial.html

13/22

5/20/2015

WindowsShellTutorial

OptionsFileTypestab.YougetalistofallfiletypesthatareregisteredwithWindows.You(oraprogramthatyou
install)canmodifytheseassociations.
Exercise17
Whichprogramisassociatedwiththeextension.html?Whichprogramisassociatedwiththeextension.gif?

ContextMenus
ItemssuchasfileanddirectoryiconsintheExplorerdisplayhavecontextmenusthatcontainscommandsdirectlyrelated
totheitem.Thismenucanbedisplayedbyclickingontheobject'siconwiththerightmousebutton.

OneofthemostusefulentriesinthecontextmenuofafileisRename.Torenameafile,rightclickonthefile,select
Renameandtypethenewfilename.
Exercise18
Whatarethecommandslistedinthecontextmenuforthec:drive?Whatarethecommandslistedinthecontextmenu
forthec:\yourname\tutorial\sample.txtfile?

MovingandCopyingFiles
Filesanddirectoriesoftenneedtobecopied.TherearetwomethodsforcopyingfileswiththeExplorerprogram.
http://www.horstmann.com/bigj/help/windows/tutorial.html

14/22

5/20/2015

WindowsShellTutorial

Themostintuitivemethodisdraganddrop:selectafilewiththemouse,dragittoanotherdirectory,anddropit.Ifyou
holddowntheCtrlkeywhiledraggingthefile,itiscopied,notmoved.
Withsomemanualdexterity,youcanalsodragagroupoffiles.Toselectmorethanonefile,depresstheCtrlbuttonand
clickonallfilesinthegroup.Forselectingmultiplefileswithsimilarproperties(suchasthesameextension,orsimilar
modificationdates),youmayfindithelpfultoswitchtoatabularview(menuoptionView>Detail).DepresstheShift
buttonandusetheUpandDownarrowkeystoselectacontiguoussetoffiles.
Thedifficultywithdraganddropisthatboththesourceandtargetdirectoryneedtobeonthedesktop.Youcanovercome
thatproblembycuttingandpastingfiles.Selectthefilesyouwanttomoveorcopy.ThenselectEdit>Cut(orsimply
Ctrl+X),movetothedirectoryintowhichyouwanttomovethefiles,andselectEdit>Paste(Ctrl+V).Tocopythe
files,useEdit>Copyinstead.

Exercise19
Copyallfileswithextension.txtfromthec:\yourname\tutorialdirectoryintothec:\yournamedirectory.What
sequenceofkeystrokesandmouseoperationsdidyouuse?(Makesuretocopythefiles.Donotmovethem!)

Backingupyourwork
Computersarefairlyreliable,buttheirpartsdohaveafinitelifetime.Also,importantfilescansometimesbedestroyedby
carelesscomputerusers.Youshouldmakeitahabittobackupallimportantfiles.Yourinstructorwilllikelynotaccept
"Thecomputeratemyfile!"asanexcuseforlateormissinghomework.
Inancienttimes,floppydiskswereusedtobackupdata.However,floppydisksareactuallymorefragilethanharddisks.
Also,thediskdrivealignmentsofdifferentcomputerscanvary,sometimessomuchsothatitbecomesimpossibletoreada
floppydiskthatwaswrittenonanothercomputer.Itisbestifyouusefloppydisksasamatteroflastresort.
Onyourowncomputer,themostconvenientbackupmethod(asof2003)isaCDburner.WindowsXPhasarudimentary
featuresetforburningCDs.YoucaninsertablankCD,dragfilesontoit,andburntheCD.However,somecomputer
manufacturerspreloadsoftwarethatoffersadifferentinterfacetotheCDburner,andolderversionsofWindowsrequirea
separateprogramsforCDburning.Sincethedetailsvarywidely,wecannotreviewtheprocessinthistutorial.
ThebestmethodforbackingupyourworkinacomputerlabisanonlineservicesuchasYahooBriefcase.Youcansave
filesonanexternalserverandloadthembackeitherontothesamecomputer(incaseyouneedtorestorealostor
corruptedfile),orontoanothercomputer(incaseyouneedtomoveyourworkbetweenyourlabandhomecomputers).
Exercise20
Backupthefilec:\yourname\tutorial\sample.txt,eitherontoanonlineserviceorontoafloppy.Describethestepsthat
youtook.Nowdeletethefileandrestoreitfromyourbackup.Whatstepsdidyoutaketorestorethefile?

TheCommandShell
YouhavenowlearnedhowtonavigatetheWindowsdesktopeffectively.Thefinalpartofthistutorialcoversthecommand
shell.Youmaywonderwhyyouneedtolearnanothermethodforachievingthesametasks.Therearethreereaons:
1. Itismuchfastertotypecertaincommandsthanclickinganddraggingwiththemouse.Forexample,supposeyou
wanttoerasealltextfilesinafolder.InaGUI,youselectalltextfilesandthendragthemtoatrashcanicon.Ina
commandshell,youtypeafewkeystrokessuchas
del*.txt

2. Youcansavetheoutputofacommandforlaterprocessing.Forexample,supposeyouwanttodosomethingwith
http://www.horstmann.com/bigj/help/windows/tutorial.html

15/22

5/20/2015

WindowsShellTutorial

alltextfilesinafolder.Youcansavetheirnamesinanotherfilewithacommandsuchas
dir*.txt>names.dat

TrydoingthatinaGUI.Ifyoutakeascreencaptureofafolderdisplay,allyougetisabunchofpixels.
3. Youcanautomaterepetitivecommands.Forexample,supposeyouhavemultipletextfilesandwanttocompress
eachofthemintoaseparatefile.Youcanusealoopsuchas
for%fin(*.txt)dojarcvf%f.zip%f

Iftherearemanyfilestoprocess,suchanoperationwouldbeverytediouswithaGUI.Manyworthwhiletasksare
neverattemptedbyGUIusersjustbecausetheydon'tknowhowtoautomatethem.

StartingtheCommandShell
OpentheRunmenuandtypecmd(orcommandifyouuseaversionofWindowspriortoXP):Ctrl+EscRcmdEnter.The
commandshellwindowappears:

Thecommandshellhasaratherprimitiveuserinterface.
Apromptshowsthecurrentdirectory,suchasc:\windows.
YoutypeacommandandhittheEnterkey.
Thecommandisexecuted.Itsoutputisdisplayedintheshellwindow.
Anotherpromptisthendisplayed,andtheprocessrepeatsuntilyouclosetheshellwindow.
Exercise21
Whatpromptisdisplayedwhenyouopenupacommandshellwindow?
Typethecommand
dir

followedbytheEnterkeyintotheshellwindow.Youwillseealistingofthefilesanddirectoriesinthecurrentdirectory.

Exercise22
Howmanyfilesarecontainedinthecurrentdirectory?Howmanydirectories?
http://www.horstmann.com/bigj/help/windows/tutorial.html

16/22

5/20/2015

WindowsShellTutorial

Nowtypethecommand
cd\

Don'tforgethittingEnter.
Exercise23
Whatdoesthepromptstringlooklikenow?
Exercise24
Whatfilesanddirectoriesarecontainedintherootdirectory?

Nowtype
cd\yourname

Asalways,replaceyournamewithyourpersonaldirectoryname.IfyourdirectoryiscontainedinadriveotherthanC:,you
firstneedtoswitchtotheotherdrivebytypingthedriveletterfollowedbyEnter,forexample
j:
cd\users\jqsmith

Next,type
cdtutorial

Exercise25
Whatdoesthepromptstringlooklikenow?
Type
cd..

Exercise26
Whatdoesthepromptstringlooklikenow?
Finally,type
cd\tutorial

Exercise27
Whathappens?Explain.

Youhavejustlearnedthebasicdirectorycommandsintheshell:
Typingcdplusapathchangesthedirectorytothegivenpath.Hereapathcanberelativetothecurrentdirectoryor
absolute.Absolutepathsalwaysstartwiththerootdirectory(\).Relativepathsbeginwithafilenameinthecurrent
directory.
Thereisonespecialfilenamethatisveryuseful:thedoubleperiod(..)referstotheparentdirectoryofthecurrent
directoryinthedirectorytree,sothatitispossibletogoupthetreewithrelativepathsaswellasdown.Similarly,the
filename.referstothecurrentdirectory,butthatabbreviationisnotcommonlyneeded.
Typingdirlistsfilesinthecurrentdirectory.Youcanalsogivedirarelativeorabsolutepath,anditwilldisplaythe
http://www.horstmann.com/bigj/help/windows/tutorial.html

17/22

5/20/2015

WindowsShellTutorial

appropriatedirectory,suchas
dir..\projects

CommandLineEditing
Somepeopledislikeusingthecommandshellbecauseitistedioustoreissuecommandsthatweremistyped.Fortunately,it
ispossibletoretrieveandmodifypreviouslyissuedcommands.
HittingtheUpandDownarrowkeyscyclesthroughthecommandsthatyoualreadytyped.

Exercise28
WhatcommanddoyouseewhenyouhittheUparrowkey?WhatcommanddoyouseewhenyouhittheUparrowkey
again?
NOTE:Ifthearrowkeysdon'tretrieveoldcommandsandyourunWindowsXP,doublecheckthatyouare
runningcmdandnottheoldercommandshell.IfyouhaveanolderversionofWindows,youneedtorunthe
doskeyprogramtoenablecommandlineediting.Simplyrundoskeyafteryouopenacommandshell.

Exercise29
TypecandtheF8key.HitF8repeatedly.Whathappens?

TheF8keyperformsasearchofthepreviouscommandsthatstartwiththetextyouhavealreadytyped.Thisisoftenthe
fastestmethodforretrievinganoldcommand.
Youcanusethecursorkeys(Left,Right,Home,End)toeditthelinethatyoucalledback.Movethecursorwhereyou
wantitandinsertorremovecharacters.Ifinsertingcharacterstypesoverexistingtext,hittheInskeytoswitchfrom
overtypemodetoinsertmode.
Exercise30
Typecd\windos(notethemisspelling).Afteryougetanerrormessage,usecommandlineeditingtofixittocd
\windows.Whatarethekeystrokesthatyouused?
Anotherveryusefulfeatureoftheshellisfilenamecompletion.IfyoutypeapartofafilenameandhittheTabkey,then
thefirstmatchingfileisdisplayed.HittingTabagaincyclesthroughallmatchingcompletions.
Exercise31
Typecdc:\wandhitTab.Whathappens?
NOTE:FilenamecompletiononlyworkswithWindowsXP.Itdoesnotworkwitholderversionsof
Windows.
Finally,ifyoulookforacommandandyoudon'tfindwhatyouwant,youcanclearthecommandlineandstartoverby
hittingCtrl+C.Indeed,thiscommandcanbeusedtostopalmostanyactionthatisstillinprogress.

FileCommands
Thedelcommanddeletesafile.Forexample,
http://www.horstmann.com/bigj/help/windows/tutorial.html

18/22

5/20/2015

WindowsShellTutorial

delsample.txt

deletesthefilesample.txt.
NOTE:Whenyoudeleteafilewiththedelcommand,itdoesnotgetmovedintothetrashcan.Itisdeleted
forgoodandcannotberetrieved.

Tocopyafile,usethecopycommand,followedbythetargetfileordirectory.Forexample,
copysample.txtsample.bak

copiesthefilesample.txtandnamesthecopysample.bak.
Exercise32
HowwouldyouachievethesameeffectusingtheExplorerprogram?
copysample.txta:\

copiesthefilesample.txtintothedirectorya:\.Becausethetargetofthecopycommandisadirectory,thecopiedfile
keepsthesamename.
Tomoveafile,usethemovecommand.Forexample,
movesample.txta:\

movesthefilesample.txttothedirectorya:\,removingtheoriginal.
Youcanalsousethemovecommandtorenameafile.Thecommand
movesample.txtsample.bak

renamesthefilesample.txttosample.bak.
Exercise33
Howwouldyouachievethesameeffectusingthecopyanddelcommands?

DirectoryCommands
Themkdircommandmakesadirectory.Forexample,
mkdir\yourname\homework1
cd\yourname\homework1
mkdirbackup

Exercise34
Executethesecommands.Whatisthefullpathnameofthebackupdirectorythatwascreated?
Youremoveadirectorywiththermdircommand.However,inordertoberemovable,adirectorymustbecompletely
empty.Thatis,youmustfirstremoveallfilesanddirectoriesthatitcontains.
Exercise35
Executethescommand
rmdir\yourname\homework1

Whaterrormessagedoyouget?Howcanyouremovethedirectory?
http://www.horstmann.com/bigj/help/windows/tutorial.html

19/22

5/20/2015

WindowsShellTutorial

Wildcards

Oftenwhenwewanttocopyfiles,weonlywantfilesofacertaintype(thatis,withacertainfileextension).Forexample,
wemaywanttocopyonlytextfiles(withextension.txt).Weusethewildcardnotationforthispurpose.
Thecommand
copy*.txta:\

copiesallfileswhosenamesendwith.txttothea:\directory.
Exercise36
Howwouldyoucopyalltextfilesfromthec:\windowsdirectorytoc:\yourname?Whyisthisabettersolutionthanthe
oneyoufoundinexercise19?
Exercise37
Whatdoesthecommand
delc:\yourname\*.*

do?
Theasterisk(*)intheentry*.txtstandsforanysequenceofcharactersofanylength.(Notehowthefileextensionisgiven
separately.)Theotherwildcardthatisavailableis?,whichstandsforanysinglecharacter.Herearetwomoreexamplesof
theuseofthesewildcards:
Thestrings*.txtmatchesallfilesbeginningwiththelettersandhavingtheextensiontxt.
Thestringst??.ba?matchesallfilesbeginningwiththelettersstwhosefilenameshavefourcharacters,andwhose
extensionsconsistofthreecharactersbeginningwithba.

Exercise38
Usethedircommandandwildcardstofindallfilesinc:\windowsthatstartwithaw,havethreeletters,andwhose
extensionisini.Whatcommanddidyouissue,andwhatmatchesdoyouget?

CommandLineOptions
Manyshellcommandstakeoptionsthatmodifytheirbehavior.
Forexample,thedircommandhasanoption/wthatproducesa"wide"listing,withseveralfilesineachline.The
commandis
dir/w

forawidelistingofthecurrentdirectory,or
dir/wc:\windows

forawidelistingoftheWindowsdirectory.
Anotherusefuloptionofthedircommandis/p.
Exercise39
http://www.horstmann.com/bigj/help/windows/tutorial.html

20/22

5/20/2015

WindowsShellTutorial

Trythecommanddirc:\windows/p.Whatistheeffectofthe/poption?
Youcancombinemultipleoptions:
dir/w/pc:\windows

Ingeneral,anoptiontoacommandstartswithaforwardslash,followedbyaletter.Notethatforwardslashes(/)are
entirelydifferentfromfrombackslashes(\),whicharepathseparators.Mostcommandshaveseveraloptions,whichyou
canfindintheonlinehelp.
Youcanalsogetabriefdescriptionofacommandanditsoptionsthroughthe/?option,forexample
del/?

Exercise40
Whatarealloptionsofthedelcommand?
NOTE:InLinux/Unix/MacOSX,youuseadash,notaforwardslash,foroptions.Forexample,lsa.

CopyingfromandtotheShellWindow
Sometimes,youneedtocopyinformationfromacommandshellwindowintoanotherwindow(forexample,toinclude
outputinareportoremail).Unfortunately,thisprocessissomewhatcumbersome.
Rightclickonthecommandshellwindow.Acontextmenupopsup.
SelecttheMarkoption.
Usethemousetoselectarectangulararea.(Youcanalsousethecursorkeys.HitDowntomovetothefirstlinethat
youwanttocopy,thenpressShift+Downtoselectthelinesyouwanttocopy.)
HitEnter
Switchtoanotherprogram(suchasNotepad)andpaste(Ctrl+V).
Obviously,thismethodcanonlybeusedtocopyasinglescreentoNotepadoranotherapplication.Togetmorethanone
screen,youwillneedtouseredirection,whichisdescribedintheadvancedlab.
Conversely,youmaywanttocopyacommandfromanotherprogram(suchasawebbrowser)intotheshellwindow.Copy
thecommand,thenrightclickontheshellwindowandselectthePasteoption.
Exercise41
Copythiscommand
dir/oen/pc:\windows

intotheshellwindowandexecuteit.Whathappens?

ExecutingPrograms
Toexecuteaprogramfromthecommandshell,youtypetheprogramname.Forexample,tolaunchtheExplorerprogram,
type
explorer

Youcanalsoprovidecommandlinearguments.Forexample,tolaunchthenotepadprogramandeditaparticularfile,
simplyspecifythefilename.
notepadc:\yourname\tutorial\sample.txt

Exercise42
http://www.horstmann.com/bigj/help/windows/tutorial.html

21/22

5/20/2015

WindowsShellTutorial

Executethecommand
notepadc:\yourname\tutorial\myfile.txt

Whathappens?Explain.
Whenyougivethenameofacommand,thenWindowstriestofindanprogramfilewiththatname.Forexample,when
youtypenotepad,thenWindowslooksforthefilenotepad.exe.Itlooksfortheprogramfileinthecurrentdirectory,then
inasetofstandardplacesthatincludethec:\windowsandc:\windows\system32directories.Iftheprogramfileisnotfound,
thenanerrormessageisdisplayed.
Exercise43
Executethecommand
notpad

(Notethemisspelling).Whathappens?Explain.
Sometimes,youneedtoexecuteafilethatisnotapartofthe"standardplaces".Forexample,ifyouinstalltheJava
compiler,itisinstalledintoadirectorysuchasc:\j2sdk\bin.Bydefault,Windowswillnotlookinsidethatdirectory.You
can,however,launchtheprogrambygivingthefullpathname
c:\j2sdk\bin\javacMyProg.java

Youwillseeabettersolutionintheadvancedlab.

Exitingtheshell
Toclosetheshellwindow,typethecommand
exit

Alternatively,simplyclosetheshellwindow.
Exercise44
Executethecommand
exit

Whathappens?

http://www.horstmann.com/bigj/help/windows/tutorial.html

22/22

Вам также может понравиться