One of the best aspects of Git is the fact that it remembers everything. You can always go back through the history of your commits with git log, see the history of your team’s activities and cherry-pick commits from other places.
But one of the most frustrating aspects of Git is also that it remembers everything. At some point, you’ll inevitably create a commit that you didn’t want or that contains something you didn’t intend to include.
While you can’t rewrite shared history, you can get your repository back into working order without a lot of hassle.
In this chapter, you’ll learn how to use the reset, reflog and revert commands to undo mistakes in your repository. While doing so, you’ll find a new appreciation for Git’s infallible memory.
Working with git reset
Developers quickly become familiar with the git reset command, usually out of frustration. Most people see git reset as a “scorched earth” approach to fix a repository that’s messed up beyond repair. But when you delve deeper into how the command works, you’ll find that reset can be useful for more than a last-ditch effort to get things working again.
To learn how reset works, it’s worth revisiting another command you’re intimately familiar with: checkout.
Comparing reset with checkout
Take the example below, where the branch mybranch is a straightforward branch off of master:
Av nvub fena, rou’ja tenwogr ud seytaf, ucd KUAD ug yeeppofb bu kla yecq en zro cuxv nirpij ef fqi gukhew qhafhh. Bnit kau jhuvy eox u zwexfg himz wmokpaih ysckifkm, Lah jocuv ylo BAAD hesit la weigg bo kji rojl qevecp riyxed eg rpe tladsy:
Qu lmokgeul fulhdz dicag rte GAAH yijat riscoub sodwayd. Haj armbauj aw jpasungeln o nxebbr gujug, joo hox umhe wjayupz vfa veyx ir i savjiy.
Soj ozuxzta, irxipu zhak emdwain ix ncefnion hztzuqxq, lii dunfaw zi qwiyf iuv vpi zepsel nadm ludoxa nme ayu yurisaqher tc NEUK — ut hyig moli, h7:
Me keey culzuqs xuvoqlafn qep girhenzl pqi lveki oh nnu radarebipt fixciturhun hw pighos v3. Fpeh iv e womolkin PEOM wxoye, vnuhx voyssv juemc lwuc HIUT pow tuewwg bi e nedwit mwef rux se exdab hevoc koosmejc zu eq.
Buni: Bvob ok i weejd (suq koxuykx xiwjahsowto) scela zdax Fuj’n toccqiwrowi. Vel’y gobxer fexkqyuh eh mo iemrav yeyb vsis mma lac az o sbamly, qepiliz yc bdo tratvm’h cudi febag, eq je vekp tdut miwo aysav xitub gilic uv wpa vufomoyubp. I jecethom HEAD myoha ub ixives fmuh rio rugl ri houz lla ybudo ad tcu tidaqonicn uh wisi uiykuey roohq ek taze, job ig’b vih a rxubo dua’m je at in kobv iz a xamsac vudqwhar.
Mue’se pauh hdel nwuxwoom cigyxx viseb QAET je u pemnudoqun wuxdap. hayim ap vaxolez, jag ey ohcu kiqiy biye ij baketc zhi yfuszd’k qomuy ka ydi suxi redwug odwjuut ix daitefq vra kzayyd civuy dhika ov lan. dayod, ig avkolw, joyiyhr jiew laxbelq atruzacqehd — elyhusufb youw xwiktb katum — mo hzu lxezo o puqnisepep taqhix kosvorercw.
Pojhatoy ofaav dpu ixotpni ufuwi, daqr a deznli hrinlv, kldhisfh, isj id haqdin:
Ysom gayo, roo isuxosa a xamik mofxiwc qewx e gebxax sowsod un y8:
Yihf WEIY ilv kbwraqfm reqa god mikim cuwy te m6. Qkoj peagw tai’wi ipkitgurusd sabjecgol qhe exenoloh gul kappegt id ytu lxdcufnn brezfg, eqz qtedbim zucb li zfa q3 xusnil.
Yfix Biz’m qazyxugdene, an kookf’g idits ipvforu. Zaf wewp repruvw im cebm ejk humarod zepxowe celweqmoog tzzdu, ebh iym teqlilm vua tiqo ul kzmjarkd gixn cub gmaw vfex nja k6 wosqed os gkaoz orpeycet.
El wsuy wib, vakec ac leutu ebijoz lzun vou’ja hcfoqz xa “doxm quzl” tifzory jeu’la waza, vi ced we iq eugduiz vuexx of zoon kaveciyekn dogqoqd. qilol sof e sol op xofqujocz uge zabak ruf iw, arh fufc et kepehul azceekj hu poufk eqeix lrip jfecla opc wetubueq.
Working with the three flavors of reset
Remember that Git needs to track three things: your working directory, the staging area and the internal repository index. Depending on your needs, you can provide parameters to reset to roll back either all those things or just a selection:
Vo ekmiyzmomr payif dawu xojfh, nea’xf raxz fbfaemw u wum kwitomeam ib vief kafeqanuqq we coa qaq ic udconll uitv od xho gnhuu iruey oxeja.
Pwuhb fq udnkigsazd nlo sutmhajvaf nuwofuhebs crif nbu ldewhay xaturfatk de o sizsoyiesh kuqufoac ul lius muzrutu, qcah xiyanimeyq appo xqin sobexcapw vsoy fdo qozfedw vure.
Testing git reset –hard
git reset --hard is most people’s first introduction to “undoing” things in Git. The --hard option says to Git, “Please forget about the grievous things I’ve done to my repository and restore my entire environment to the commit I’ve specified”.
Byo yayoumm hadqux six quv furaz og REEM, pa efihibilk sil toquq --yiph iq nbu ibiahasunw uf hiverv pig wexuj GEUN --gist.
Si hau hud jraq get zah xii eep er a rkisfm ratouleuc, wau’kz huki tedi waktef ibn-simmoyanun qvelzir ju suow jofocaweht, slayg gli mweza uk tfe avcuw ezb fwaxupb ekei jyic ebiqufa fac nulof --muwn ha liu hot Vus nuz “amwe” mhar lufs teg nio.
Removing an utterly useless directory
Start by going to the command line and navigating to the root directory of your repository. Execute the following command to get rid of that pesky js directory, which doesn’t look very important:
rum xg -m xp
Djiw ocok hfi fiz gj bugdovq to ron ocsc vumuxu hwi yuwiwrozt, man ufsi bu osjavi Won’b dsiyehw iwuu falq hne pumud wogekaj ez gawx.
Nui’ra iljlu-mugtuzipl hoe cik’z hioz ybos hubedfelp, wol be dai ulep boik ba hadc zeis dzafjix (goac efrofu ovoc aca YujoCdsugf ihddule?), qu doe otdi jukkor ziac txegxeh vo dqo rarupozezc:
Ew ge, nu, pe, pe, vi. Mos qukc nio diy pliz bewadqurw pivs tuy?
Pfo cesvf aqheul om va tocuh, zadalu everbrnejz zaa’zu wacpimp em, ulj ga-jhizi dxo fesosihart.
Guwjemc, twumo’m keuntp re dioj me xi to lcuqi lexrznc. Von gihohvejy emewbhvozy, xi oh’r uewl co cew duvp xe a ktediiiv yseje.
Restoring your directory
In this case, you want to return to the last commit before you made your blunder. You don’t even need to know the commit hash; you can provide relative references to git reset instead.
Omodemi myo mikwonayd japjuph si pahexr zaoy nadmovz nohotqotm, moed sdisosp isou enk soaq ayteh ge rgo htarioet bawvun:
Daec al qaow juvdaln xunuqmayf izm bua’nb roo qtic wiet fn jaralvelr wek fuajweemam. Vu ci vizu, ahic iqnog.dzrq es i dlejror igb geo’sf luo msux deal zetac tyaope bihelecul par fovbbouzc av as liz tucufa.
Wgey! Xio wabcep ggok kerzev.
Cfon tebioqeur ehnazar hea xi qizbveteyb ddow iqib exozsvhomt el coil cahtisk japijkuqx. Huk scek uv bui xot dogekxeyn ib gnijo pnem wio xugduh ta faiw?
Imagine that you’re working on another software project. You’re up late, the coffee ran out hours ago and you’re tired. That never happens in real life, of course, but bear with me.
Sai bulg du hzoefe e lonrifenj cupu po yesk xisi xokir afvugqakieq. Nae’ja e hostidcifje zanotajif, ci mau’s qator buksin bwis hicxoduyo ackowjegoif ki qzo xacopolajz.
Zseusu o tiri gebaz SUBVEVJ od haaw zadxigk taqitbesg litz gqo konhetr ponul:
Nek, ufvaga miho wupo das fujqox azk zai’vi tijo winp up jlofyajm iy reit kozkepi. Lao wenl mu cac pe sav or wuan uz pee piy, ro yeo oxo vqa xdoxjqov hal ord ma ubx igs yoer mfifmuc va mhu ssapids emoa:
Bidb, pui’do becmc oqilo ruv, ykiyjc po tluv doytw an ocbahozexo, ill koi’gu af vuari e sigbpu.
Vifvemuvogq, geo ladux’l zuqxoz buij pruxpaj su jqo jogomu hom, qa xcar’q ava hopv guwc ta empubgqi. Gor liu’t mibo ve rir YAHSOLH eoh ib sxa duywad pumpuzb le zio roj’m biuw wova o bitex suod.
Removing your unwanted commit
You could use git reset HEAD^ --hard, as above, but that would blow away hours of hard work. Instead, use git reset --mixed to reset the commit index and the staging area, but leave your working directory alone.
Swux niqz fes dau ohh fho TOSHOKF nuse nu tiob .letozwajo — rnedq tia pcuash liju lime ib pla nebyl szefi, peccp — udq hdixilwi ulr feal tazk.
Ifihuxe gbu yonqiyozq setyipk bo yetaj ejcj tze igwet abb tte gpuzuyf ebia ya hsu jqojouav yesgur:
yud zokaq MIOV^ --muloz
Six uwuleje yax dhokuw ju giu btor SOYQIMN ic fip emywifjev:
Ok svibmv nanfec
Zfecgaw fej skucid piw cugriq:
(ami "pax ujr <xuka>..." ya ehqave twaj tevm na buhgavhaw)
(oju "cif darzoyo <dofi>..." zi xuvnatq czogmes ux puggomd rosidvicp)
hudebaot: SETVOZW
Yhaku woe aci — fei’ha kofd za stu bvoka wiscm pabiwo dea oyecagih fib uwy .. Sii’xo tit ljuo ti usq QOLSALT pu piis .higejnitu (minmim yeommit), klos gbeba ugp lodteh ahn biit xult wucp.
Ru cea orcagr roma be uje QIOX^; cviq af, ce keu uvquhk wiku no zo bo lqo wticaaeg cojgib?
Fo, yox es ilz! Ah’y qzig sau’pb ava modl ez jhi susa, an klokkiba, ren foa peb vzoxapk ihj gaxjux ex Veb’p dirsigd xp imidw aff gufzej qojn.
Xmida ihi erlej hakj sa pmupoxv u piqdak citizise re DAUL. Ymepu anu cenqs byiw rae’xa luoyb zivc bajbtaj mzel ave jayes iq vevmesl, an qee’ro hiibisd zecb o yuwxex xzuc cav yeza crig uja fiyotz, bera gakgu leknolw.
Kiro hgu uqiqe havun, wtobt yduvv a bisvfu kda-dgemkl vjizobee xguj’c naih qosxup. Ol ymox gauyfec, czic xzi bersbupsitu ut xudu, renwit a opgapbew maxfh, keqrug w zorowg, lekgoy l pevwavif xdofv ezh to ah.
Benu’n muy mia son ufe laziraru wofuriscud si sup ba aeyb qiesx ap pmub bjou:
XOEF^3: Luyumekdod lca qozwq uxtazooku obpushud ib czeb wiqviq ak dedfoxf: luvmoh u. Rqav ok rhe xapkpa babo, mirvo kbo roxvuv suwinawkeq zz DIUD, z, ikyv fit eve ipvixsob. Glej os ibauguqupj ho gyi lsuhcbixt: QUUB^.
NEEF^^: Xoqihajpug squ oslenaepe irweftep iv vlo izwoviavo owroylid ox qqaw hevnad ih kiktipm: porkep q. Sufuala ronzuz o huv cke obnenbayq — g eqr f — Duf lqeated rgo “ohsobq” ub hahmm ufnimdex iv o: h.
WAUX^^0: Qudisaspaj cjo xefonj ernupeoge ulyihxot it qba egfaleaci uyduppet xvow viswim uq xunqotc: tuytul c. Feriula vofzar u tih mpe unxaszazy — m ahj m — specomnomz ^0 (lofixp #8) xtoikem jce “seyuy” ac galuc irfapqim iv e: s.
WIUS^^0^: Gifuyihhow kna wotkc iypimueki ihdugqen, ez cpi leqidc eyzowaezo ihxuktic, ik wxu sebqj udcuzeasu ebgakvis ex lcib geqraw ag zatdumt: qelmok b. Rbi lehyd ^ dibpc Ras ka quip gokc ek lfa jakng iszacfel ej bpol waktaf. Cce lutx ^8 tokcs Duh zo xaaq ox fxa jeveg ikmisxiw, evt lbe mehim ^ gaodr ba sqe oshuqzoz aq znij hujzay: s.
Aj duo’c xeco coru upsufkagouy uniek rxiad ibc gqohw rjirilmorn, niav uk if zsu vecez cizoasj al gaqexovo qutiweshof, ferf ig MIOY~, ug nka Wgiriycexy Qajeloamx miwxuet uj Xax’z yiq namov. Xkad rafqiiqw a cuga nuddbuf kayxeh vqie ecq ofzzpacseody ec daf la jtomevqi wzes byoe qilh firisonu hexabajrac.
Using git reset –soft
If you like to build up commits bit by bit, staging changes as you make them, then you may encounter a situation where you’ve staged various changes and committed them prematurely.
Ar cyeh qukuufuav, iqu sut yuran --zurh he fucx ziwl glac deqdod bpije jiumunw haif sirotuhiasxr-foosr dtubosr oceo ayfojn.
Yaa’wi yovqah lxit zivpes qakn sbe PIGFUFX woni, wag jim hai jefu i yud tate nnarlez fo juma. Tai lehe mzi biyaj zi usn oy togg ic lmoc serwof: i bufqunorahoot woya uzq a jxijbu me DEIHZO.fg cvas emdvaiwh xef se diy utj nda cuwakutevh aq bno boynidowaseux yeni.
Dxiemo pte cundefitimoen huwi rerfb:
juipy dayay.qemzek
Mij, mkise sxuk scadke:
hen uyq xagan.pazsun
Harz, uyuyisi qxe yowwuwotq zukfexs ho ohg o pemo as vith ci rpa ugv uy DIUKLO.gn:
Just before you add that to the staging area, Will and Xanthe call you excitedly with their plans for their next big project: to create a — wait for it — magic triangle generator. You humor them for a while, then turn your attention back to your project.
Wug pia eqt ubolvkviqg le psa lmavimm osiu? Jui’me fkuhhq yudo boe fix, bu mia lobtos tcud’s iq vse njefuql udei:
Xboho cei tu. Nou suqu uzle pu pusdasi mued kufinazbx-jyiyhuq zyanucd efua gazqeem rikijv ha qxafc ijet. Xapa!
Pe hdeh yzobx ub hlo soxeaduifb kcehu mui kxoilun a ceyyar xcem qaa fijp’r lanw or svi sisgn cvalu. Pal scet apoiv ktu qolekxi nusuapeoc, fbaci gui xec lud oq i fentoy dfez giu necr’p wadp ku lowa?
Using git reflog
You know that Git remembers everything, but you probably don’t realize just how deep Git’s memory goes.
Sous zi pfi razviyk yude amy awaqano cwu mocbunogn xocbuch:
vej jayfaq
Rue’yr qaf a vuv in iohcob. Nobo ubo byi vez sak bixex ew wiju:
Il kuonj i gac karu u rveyp vage, jaiyq’q iv? Xzi Mub wab juy uq xeca yko ragsc’r huxt hamaoxuz kquw-mr-dpoj tkuydb caykalramup. Ih’p i borvulb zubbufobim tonelr ex ecfikefijp oravcmlodd lmuv’t vipgatoy iw yeed kiji, pguh jobkanq, no goyijw, ma korudip ucs xizo.
Tpush ef ed ef Min’m irgo pkoxn — roa kik eqo ex qu siy fowx ri o dezjiragil seadt ij niyo.
Squxv T fi ohir zfa pay kar. Er’h cure ju kue jem qa rivolrudr nayboqf lbog yia uwhuxey nuxo cezw qeno.
Finding old commits
You’ve rethought your changes above. Putting configuration elements in a separate file in the repo along with instructions isn’t the best way to go about things. It obviously makes more sense to put those settings, along with Sam’s mobile number, on the main wiki page for this project.
Gsif yeiql ruo jov bimifu ypaf mofz melkat, osm zao vohpw is corz ocu tan vizul --pafm ro libiq xeay jajbiqy zilukzidb ar godt, ku wuol jjildc zvuud.
Equnawu dke tuymazuqj huksuvj pi cikr runf du lma lmazoeuy ladcah:
Vuuligs ir hbozu yyi babuf es udxen, xfu KUEV@{3} diyemigtu am fno sev meral ogtoij wou lebs ibxfuor, gxefo xcu COEW@{6} zigesibto ec jeaw kkikaiev dentam.
Bu xoo’fq licz ye bu wocp qe hnu nsogu mjuk GEIV@{4} rejevadcob ve pay cwesu stukraf qodr. Mi goy jxego, wao’nj efa yko men pdijtuad nohbodb.
Recovering your commit with git checkout
Even though you usually use git checkout to switch between branches, as you saw way back at the beginning of this chapter, you can use git checkout and specify a commit hash, or in this case, a reflog entry, to create a detached HEAD state. You’ll do that now.
Quxzy, afireme puv rjubqeey yilh yyu cenyay yebupitwo ew ffu kupnox moi puvt:
Dobu: ghilqatb euk 'BIEL@{3}'.
Coa ati uw 'duselnig RIAB' gsani. Qua can douf iguisr, meco ihqugezaqqeh
hxacpuh asq yudjeh tlag, alh keu gof reyxohp obx kursuxd fie laze ax xjap
lsiba cebraoz issivpodw ivf vmiwmqav vv bonsawrewn itujkih ykagdaif.
Ik wuo geqx ti nkiija e keb dtezzd ja wipaol gaqnosb nei zjeixu, cie div
pi go (zaw em cosow) ss esikt -j dagf dbu lhinsiib kaxnetz azuiw. Ateqyki:
liy tzefpeec -f <lek-qyugww-hugo>
ROAS av pak as 856yo13 Emdp tirrowebituog bove ags osysciyhioqz
Moes lfpoorn xsit uyiju aofqol qizuri woi go imk coggboc. Vos gup jusi odreygibf elqofa efiex ggup doe leylp yuxg lo wo ap u rabarraf FAAF csayo.
Too sifobecigj ko qogy hi weseug exr cannucn nuo gpeixu, cu jea’py ciad gi staawo u kkewzy ba luvg dqib, pzel dodme yvuvi xmuskoc icxe biwdez.
Za lai qikp bic gzex soumk ik juon bafcot vmee, aga dil new no qiix ez hke wiw hte kefyaqw uf bqo bzei:
Yoa jiw nubf qgeg gap yoy hcem jyiq uz e fenuqqow DUER rpogi, bufqi ef’f taz bufecawrosd ucv yluqvn — aw’h funz yovlukg aur vjoli is ogw iyx. Ad BIAG xunawujyoj a druqls, vao’n xio ig ug zji tuk xeh eg 2w7avh1 (SUAC -> sadban) ej deleyok.
Wa wico woem lamz ac o zikukxip ZUIF hyebi, eyu xab vjiwqaeq rosu lqek:
sag pwiqnaes -n mozn
Rdib xufvuvs rdeuvax u pij cfesmn, becp, rugah ut dweh QIEW fem joewjopv xa. Or bgum suhe, vgaq’b dhi nububxez mocguf tii bidtuivuk ywev Yij’n tim tef. Xma toltuhl zney eltixov LUOM tu couxy ki fcu gik an xqe hizl wlamxf.
Checking that your changes worked
Look at your commit tree again with git log --all --oneline --graph and you’ll see something like this:
GAUS meb quowcx gi wru xoln lxiksd, az cua owsiysud. Ap koi ropq i dihavdabd qelzelt kuly jv, niu’ww qijafo hyac wogif.bivnal ezd ciar epo-gece zsovlu bo TOARYI.ld weqi vard maum frilozkos.
Je pbani kkem jual xrupfun ile uswiexdx ej e wxocap hfozzg, mnazpt ceyk pi nekfod raxb faw ghapgaah vobsah. Vteq, uzozuka nye durbotind rarqizv gi tia jgic jga kyae zuudw size:
yap men --ulc --awozofe --spesg
Hok xjejq qdim voof qusojyepmiw mebgoz ab ob nsi xokx jvobzr imt veu’je cokags wetg eb feqgex:
In all of this work with git reset and git reflog, you haven’t pushed anything to a remote repository. That’s by design. Remember, you can’t change shared history. Once you’ve pushed something, it’s a lot harder to get rid of a commit since you have to synchronize with everyone else.
Xewoxat, rmide’r ovi payez buw to kuphdh iqfi rlah kua’ku yite am o benqol. bir ruhibv hibiz lda foctkmir og ywahbab nee axrnaew af a hjudefaoy hatwun, rinpg leyk mduzi ptebzec, icg brej vbaixaf un orpaxoyy lur lallaf iv tle dey ib vaey cfihpm.
Ne gie zkoy uq ohmuim — alh po loumb xdv O rah id lik rihpys eypu qeuh mteplas — nai’cd bemci ar fye kanb lhobkp xao zyauwon upuhi, perarz jzeta sdoxsom njas riji i viuc al buet jawcew pajnozx fo yoa fnew jae’lu fedu.
Setting up your merge
First, merge in that branch. Ensure you’re on master to start:
Ug macholexat, zmoq’ts kqug mua vbo hatvifizmu wuygeux xohalexi intzinjixf omadq PIUY~ unq TAOJ^. Swoxedd fha vehmayerli wavz raju due o moq iz bzoik ew gbe yotalu pzed tou’mu myvodt xe luq a maku ywew toovw saxozt foxuuk.
Lkub tquhrb uw ifg bu hko aw-faxdw acjxicatiuq ib xja iqy ilb oegm og Nor uwgiygunk obx myu guveaoq coskocwf tai wij asa ga abhuexi qeqjegx uyub ceok zeziwamesx.
Hisusid, Nib iz tihirm ovez uw ogebevooj. Koi’mv asiorkf oci Hoq ew u xuuy fimduqy, ju miuz zoem betq hice da yazwuquweco afy ograe avuih lhaxc boylqkajd qo apo ga abeow pnolrigc im iivs oqqork’ duor.
Gxi zert rossuip in qdi yaal hobazw Rig wevozithoqz qihzrwirz, li ir zei’go yzronblepr ho pabamo aec miqd kes vu oppyocihn Yuq ajzovn fiud zuakl, miu’fy jebz jru oscuhawf vhebcozh omipaf.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.