Table Of ContentDownload from Wow! eBook <www.wowebook.com>
WhatReadersAreSayingAboutPragmaticGuidetoGit
I’dheardalotofthehypesurroundingGit.Itwasn’tuntilIreadTravis’
bookthatIlearnedwhypeoplearesoenthusiasticaboutit.Travisdoesa
greatjobexplainingthepowerofGitinadigestibleformat.
IvoJansch
PHPevangelist,author,andfounder,Egeniq.com
Gitcanbeintimidatingandfrustratingtonewusers.PragmaticGuidetoGit
alleviatesthatpainwithastraightforward,concisewalk-throughthatarms
readerswithexactlywhattheyneedtouseGitproductively.
LuigiMontanez
Softwaredeveloper,SunlightLabs
Thisbookisamust-haveforanyoneusingGitorjustgettingstartedwith
Git.IthassavedmetimeinfindingthebestpracticesformanagingmyGit
repositoriesandwillsitonmybookshelfasthego-toresourceforanything
Git.
JohnMertic
Seniorsoftwareengineer,SugarCRM
WithtwoyearsofexperiencewithGit,IthoughtIwouldhaveknownmost
everythinginPragmaticGuidetoGit.Afterreadingitcovertocover,I
learnedthat’snotthecase.It’sawell-organizedcollectionofusefulGit
techniquesforallaudiences.
LukePillow
Softwareengineer,pillowfactory.org
Download from Wow! eBook <www.wowebook.com>
Pragmatic Guide to Git
TravisSwicegood
ThePragmaticBookshelf
Raleigh,NorthCarolina Dallas,Texas
Download from Wow! eBook <www.wowebook.com>
Many of the designations used by manufacturers and sellers to distinguish their products are
claimedastrademarks.Wherethosedesignationsappearinthisbook,andThePragmaticPro-
grammers,LLCwasawareofatrademarkclaim,thedesignationshavebeenprintedininitial
capitallettersorinallcapitals.ThePragmaticStarterKit,ThePragmaticProgrammer,Pragmatic
Programming,PragmaticBookshelfandthelinkinggdevicearetrademarksofThePragmatic
Programmers,LLC.
Everyprecautionwastakeninthepreparationofthisbook.However,thepublisherassumesno
responsibilityforerrorsoromissions,orfordamagesthatmayresultfromtheuseofinformation
(includingprogramlistings)containedherein.
OurPragmaticcourses,workshops,andotherproductscanhelpyouandyourteamcreatebetter
softwareandhavemorefun.Formoreinformation,aswellasthelatestPragmatictitles,please
visitusathttp://www.pragprog.com.
Theteamthatproducedthisbookincludes:
Editor: SusannahDavidsonPfalzer
Indexing: PotomacIndexing,LLC
Copyedit: KimWimpsett
Layout: StevePeter
Production: JanetFurlow
Customersupport: EllieCallahan
International: JulietBenda
Copyright©2010PragmaticProgrammers,LLC.
Allrightsreserved.
Nopartofthispublicationmaybereproduced,storedinaretrievalsystem,ortransmitted,inany
form,orbyanymeans,electronic,mechanical,photocopying,recording,orotherwise,withoutthe
priorconsentofthepublisher.
PrintedintheUnitedStatesofAmerica.
ISBN-10: 1-934356-72-7
ISBN-13:978-1-934356-72-2
Printedonacid-freepaper.
P1.0printing,October2010
Version:2010-10-29
Download from Wow! eBook <www.wowebook.com>
Contents
Acknowledgments 8
Introduction 9
WhoIsThisBookFor? . . . . . . . . . . . . . . . . . . . . 9
HowtoReadThisBook . . . . . . . . . . . . . . . . . . . . 10
HowGitIsDifferent . . . . . . . . . . . . . . . . . . . . . . 12
TheGitWorkflow . . . . . . . . . . . . . . . . . . . . . . . 13
OnlineResources . . . . . . . . . . . . . . . . . . . . . . . 16
I GettingStarted 17
Task1. InstallingGit 20
Task2. ConfiguringGit 22
Task3. CreatingaNewRepository 24
Task4. CreatingaLocalCopyofanExistingRepository 26
II WorkingwithGit 28
Task5. SeeingWhatHasChanged 32
Task6. StagingChangestoCommit 34
Task7. CommittingChanges 36
Task8. IgnoringFiles 38
Task9. UndoingUncommittedChanges 40
Task10. MovingFilesinGit 42
Task11. DeletingFilesinGit 44
Download from Wow! eBook <www.wowebook.com>
CONTENTS 6
Task12. SharingChanges 46
III OrganizingYourRepositorywithBranchesandTags 48
Task13. CreatingandSwitchingBranches 54
Task14. ViewingBranches 56
Task15. MergingCommitsBetweenBranches 58
Task16. RewritingHistorybyRebasing 60
Task17. DeletingBranches 62
Task18. TaggingMilestones 64
IV WorkingwithaTeam 66
Task19. AddingandRemovingRemotes 70
Task20. RetrievingRemoteChanges 72
Task21. RetrievingRemoteChanges,PartII 74
Task22. SendingChangestoRemotes 76
Task23. HandlingRemoteTagsandBranches 78
V BranchesandMergingRevisited 80
Task24. HandlingConflicts 82
Task25. HandlingConflictswithaGUI 84
Task26. TemporarilyHidingChanges 86
Task27. Cherry-PickingCommits 88
Task28. ControllingHowYouReplayCommits 90
Task29. MovingBranches 92
Reporterratum
Download from Wow! eBook <www.wowebook.com>
thiscopyis(P1.0printing,October2010)
CONTENTS 7
VI WorkingwiththeRepository’sHistory 94
Task30. ViewingtheLog 98
Task31. FilteringtheLogOutput 100
Task32. ComparingDifferences 102
Task33. GeneratingStatisticsAboutChanges 104
Task34. AssigningBlame 106
VII FixingThings 108
Task35. FixingCommits 110
Task36. RevertingCommits 112
Task37. ResettingStagedChangesandCommits 114
Task38. ErasingCommits 116
Task39. FindingBugswithbisect 118
Task40. Retrieving“Lost”Commits 120
VIII MovingBeyondtheBasics 122
Task41. ExportingYourRepository 124
Task42. DoingSomeGitHousekeeping 126
Task43. SyncingwithSubversion 128
Task44. InitializingBareRepositories 130
A Glossary 132
Index 136
Reporterratum
Download from Wow! eBook <www.wowebook.com>
thiscopyis(P1.0printing,October2010)
Acknowledgments
Like any book, this is the result of much more than an author such as me
sittinginfrontoftheircomputertypingabunchofwords.Pleasegivemea
fewminutestothankthoseinvolvedinbringingthisbooktoyou.
First,I’dliketothankareaderofmyfirstbook,whoshotmeanemailthat
plantedtheseedthatbecamethisbook.
Next, Dave, Andy, and the entire crew at Pragmatic Bookshelf have been
great to work with a second time. Both books I’ve written for them have
beengambles—firstasarookieauthorandthenwiththisbookasanauthor
chartingtheterritoryofanewformat—andtheyhaven’tblinkedaneye.
Myeditor,SusannahDavidsonPfalzer,hasbeenindispensable.Shewasal-
waystherewithadvice,tips,theoccasionaltoughlove,andanever-optimistic
attitude;everyauthorshouldbesolucky.
Reviewersofearlydraftsofthisbookprovidedmewithatremendousamount
ofconstructivefeedbackthathelpedshapedthisbookintowhatyou’rehold-
inginyourhands(orlookingatonyourcomputer’sscreen).ThankstoJoel
Clermont, Javier Collado, Geoff Drake, Chad Dumler-Montplaisir, Wayne
Huang, Michael Hunger, Ivo Jansch, Jerry Kuch, Johnathan Meehan, John
Mertic, Luigi Montanez, Karl Pfalzer, Luke Pillow, Christophe Portneuve,
TomSartain,StefanTuralski,TomVanHerreweghe,MattWarren,andNick
Watts.
Noacknowledgmentsforabookonanopensourcetoolwouldbecomplete
without acknowledging the work of the legion of volunteers who made the
projectpossible.AhugedebtisowedbyallofuswhouseGittothenearly
700peoplewhohavecontributedtotheproject.
My family and friends, in particular my wife (whom I’m lucky enough to
count as both), have been amazing—as always. Without their support, and
thatoftherestofmyfamilyandfriends,thisbookwouldnothavehappened.
Download from Wow! eBook <www.wowebook.com>
Introduction
The world of version control systems (VCSs) has undergone a major shift
over the past few years. Fast, reliable, and approachable distributed version
controlsystems(DVCSs)suchasGithaveburstontothesceneandchanged
the landscape of open source software development and corporate software
workflows.
Thisbookisyourguidetothisnewparadigm.It’snotacompletereference;
instead,itfocusesongettingyouupandrunningquickly.PragmaticGuideto
Gitcoversthe95percentofGitthatyou’lluseatleastonceaweek,aswell
asafewtasksthatwillcomeinhandybutaren’tusedasoften.
Git started when the license of VCS software that the Linux kernel used to
track changes was revoked. After investigating the other alternatives, Linus
Torvaldsdecidedhecouldwriteabetterversioncontrolsysteminafewweeks
thanwhatcurrentlyexisted,sohesetofftodothat.
Git,theninaveryroughform,wastheresultofthattwoweeksofhacking
togethersomeshellscriptsbackinthespringof2005.Linushadtocalculate
pieces of the commits by hand on the first few commits (commits are the
changes Git tracks for you). Since those original hand-rolled commits, Git
hasbecometheleaderinthefieldofDVCS.
Who Is This Book For?
ThisbookisgearedforsomeonenewtoGitwhoislookingtogetuptospeed
quickly. This book is for you if you’re already familiar with another VCS
suchasSubversionandarelookingforaquickguidetotheGitlandscapeor
if you’re a quick study and want a concise guide. It’s organized by task to
make it easy to translate from the task you need to accomplish to how the
processworksinGit.
Ifyou’veneverusedaversioncontrolsystembeforeandthoughtSubversion
wassomethingyoudidtooverthrowgovernments,thisbookwillgetyouup
andrunningwithGit.Formuchmoredetailonversioncontrolconcepts,you
shouldreadPragmaticVersionControlUsingGit,1myotherbook,aswell.
1. http://pragprog.com/titles/tsgit/
Download from Wow! eBook <www.wowebook.com>
HOWTOREADTHISBOOK 10
How to Read This Book
Thisbookisorganizedinpartstoguideyoufromstartingoutthroughmore
complex situations, with each part broken down into tasks. Tasks follow a
specificformula:theleftpageexplainsthetaskandthecommandsrelatedto
it,andtherightpagegivesyoutherawcommandswithalittlebitofinforma-
tionaboutthemandacross-referencetorelatedtasks.
Youcanreadthisbookinpaperformasanopenbooktoseethetasksside
by side, but it’s also an excellentreference in digital form, especially when
searchingforaparticularGittask.
If you’re reading a digital version of this book on a computer with a large
enoughdisplay,Irecommendsettingyourreadertodisplaytwopagessideby
sideinsteadofasinglepage.Thatgivesyouthesamevisualthat’sintended
inthebook.
Onyourfirstpass,Isuggestthatyoureadtheintroductionstoeachpart.They
giveyouabroadoverviewofhowtoapproacheachpartoftheGitworkflow,
aswellasasynopsisofthetaskscontainedinthatpart.
Armedwithhigh-levelinformation,youcandeterminewheretodivein.You
canreadthisbookfromstarttofinishorcherry-pickthetasksrelevanttowhat
you’retryingtoaccomplish.
Thepartsofthisbookareorganizedtowalkyouthroughthevariousphases
ofuseinGit.
• PartI,GettingStarted,startswiththeabsolutebasics—installingand
configuringGitandcreatingyourfirstrepository.
• Part II, Working with Git, covers the basic commands you need as
partofyourday-to-dayinteractionwithGitbyyourself.Thesearethe
buildingblocks,andthey’reamust-readifthisisyourfirsttimeusing
Git.
• Part III, Organizing Your Repository with Branches and Tags, intro-
ducesbranches,apowerfulandcentralpartofGitthat’snecessaryfor
understandinghoweverythingworkstogether.
• PartIV,WorkingwithaTeam,coversthemostpowerfulaspectofany
VCS: collaborating with other developers. This part gets you up to
speed on how to share your work with other developers and retrieve
changesfromthem.
• PartV,BranchesandMergingRevisited,buildsontheinformationin
Part III and teaches you how to handle it when things go wrong, as
Reporterratum
Download from Wow! eBook <www.wowebook.com>
thiscopyis(P1.0printing,October2010)