Skip to content

Volume ITechnology

13.11.7 — Power Tools: Stash, Cherry-pick, Tags, Bisect and Worktrees ​

You are halfway through a feature. Your files are a mess, nothing works, and your manager walks over: "Production has a bug. Can you fix it right now?"

You cannot commit the mess. You cannot switch branches with it either. What do you do?

This page covers the tools for moments like that, and a few more that you will reach for once a month: tags to name a release, cherry-pick to copy one fix, bisect to find which commit broke something, and worktrees to work on two branches at the same time. Every one of them is small, and each can save an afternoon.

1. Stash: a shelf for half-finished work ​

The stash is a shelf. You put your uncommitted edits on it, your folder becomes clean, and you can take the edits back later.

Working directorycart.ts modifiednotes.txt new filehalf-finished workThe stash (a stack)stash@{0} neweststash@{1}stash@{2} oldestgit stash push -ugit stash popAfter the stash the folder is clean, so git switch works with no complaints.git stash apply puts it back and keeps a copy on the shelf.
The stash is a shelf. git stash puts your half-done edits on it and leaves your folder clean, so you can switch branches. git stash pop takes them off the shelf and puts them back. The shelf is a stack: the newest item is on top.

Here is the situation from the start of this page, step by step. You have edited cart.ts and created a scratch file, notes.txt.

text
$ git status -s
 M cart.ts
?? notes.txt
$ git stash push -u -m "half-finished idea"
Saved working directory and index state On hotfix: half-finished idea
$ git status -s
$

The folder is clean. Look at the flags. push is the command that puts something on the shelf. -m gives it a label so you remember what it was. And -u means include untracked files. Without -u, a plain git stash leaves notes.txt behind, and that stray file can still break the build after you switch branches. Use -u by default.

Now you can switch and fix production:

text
$ git switch main
$ ...fix the bug, commit, push...

When you are done, look at the shelf and take the work back:

text
$ git stash list
stash@{0}: On hotfix: half-finished idea
$ git stash show -p stash@{0}
diff --git a/cart.ts b/cart.ts
...
+// half-finished idea
$ git stash pop
On branch main
Changes not staged for commit:
	modified:   cart.ts
Untracked files:
	notes.txt
Dropped refs/stash@{0} (c352c930385ba328aa6e382284ba51cf77f493d9)

git stash list shows everything on the shelf, newest first. git stash show -p previews the changes inside one entry. git stash pop puts the changes back and removes the entry from the shelf. Notice that it brought the work back on main, not on the branch where you stashed it. A stash is not tied to a branch. You can unshelve it anywhere.

The commands:

bash
git stash push -u -m "label"    # shelve (tracked changes, and untracked files)
git stash list                   # what is on the shelf
git stash show -p stash@{1}      # look inside an entry
git stash pop                    # restore the newest and remove it
git stash apply stash@{1}        # restore an entry but keep it on the shelf
git stash drop stash@{1}         # throw one entry away
git stash branch new-name        # make a branch from the stash and restore it there

apply versus pop. apply leaves the entry on the shelf. If the restore causes a conflict, pop also keeps the entry, so you do not lose it while you sort things out. Use apply when you are unsure.

Two warnings. Stashes are easy to forget. A shelf with eleven nameless entries is a mess, so always use -m. And git stash clear and drop delete stashes. The stash is made of ordinary commits underneath (see section 7), so the id printed after Dropped can bring one back with git stash apply <id>. But do not rely on that.

2. Cherry-pick: copy one commit ​

Your team keeps a release branch with version 1.0 running in production. On the dev branch someone fixed a rounding bug in checkout (commit X), and also started a big unfinished feature (Y). Production needs the fix, but not the feature.

You do not want to merge dev. You want to copy just commit X.

dev has a fix (X) and an unfinished feature (Y)ABXYRdevreleaseAfter git switch release then git cherry-pick XABRX′releasea copy of X with a new id
git cherry-pick copies one commit onto the branch you are standing on. The copy, X′, has the same change but a new id. The other commits on dev stay behind. This is how a fix reaches an old release branch.
text
$ git switch release/1.0
$ git cherry-pick -x 15f28f4
[release/1.0 e2039c3] Fix checkout rounding
 1 file changed, 1 insertion(+)
 create mode 100644 fix.ts
$ git log --oneline --graph --all -6
* f4b319c Start next feature
* 15f28f4 Fix checkout rounding
| * e2039c3 Fix checkout rounding
| * ab15a75 Release 1.0 marker
|/
* 688585e Start the shop

git cherry-pick <id> replays that one commit's changes on the branch you are on, as a new commit with a new id (e2039c3). The original (15f28f4) stays on dev, and the feature commit did not come along.

The -x flag adds a line to the commit message:

text
Fix checkout rounding

(cherry picked from commit 15f28f4099ade57d97cf86990325253f10a69d20)

That line is how someone later finds where a fix came from. Always use -x when copying between long-lived branches.

You can copy a range (git cherry-pick A..B copies everything after A up to B) and you can apply the changes without committing (-n, for "no commit") if you want to edit first. If a conflict happens, the flow is the same as a rebase: fix, git add, then git cherry-pick --continue, or --abort to cancel.

Cherry-pick is a precise tool. Do not use it as a habit to avoid merging. If you copy many commits between two branches, you create duplicates that confuse later merges.

3. Tags: names for releases ​

A branch label moves when you commit. Sometimes you want a label that never moves, to say "this exact commit is version 1.0". That is a tag.

ABCDEv0.1v1.0mainHEADtags stay put · main moves with every commit
A branch label moves forward every time you commit. A tag label is fixed to one commit and stays there. That makes tags the right way to name a release: v1.0 will always mean exactly this commit.

There are two kinds.

text
$ git tag v0.1                                    # lightweight tag
$ git tag -a v1.0 -m "First public release"      # annotated tag
$ git tag
v0.1
v1.0
$ git cat-file -t v0.1
commit
$ git cat-file -t v1.0
tag

A lightweight tag is only a label on a commit, a file in .git/refs/tags/. An annotated tag is a full object (Chapter 13.11.5) that also records who made it, when, and a message. It can be signed with -s to prove who created it. Use annotated tags for releases. git show v1.0 displays the tag message followed by the commit.

By convention tags are named v1.4.2, using semantic versioning: three numbers, MAJOR.MINOR.PATCH.

PartIncrease it whenExample
MAJORYou break something that worked before1.4.2 to 2.0.0
MINORYou add something, and old code still works1.4.2 to 1.5.0
PATCHYou fix a bug, nothing else changes1.4.2 to 1.4.3

Tagging an old commit and sharing tags:

bash
git tag -a v0.9 -m "Beta" a1b2c3d     # tag a commit from the past
git tag -l "v1*"                        # list tags matching a pattern
git push origin v1.0                    # tags are NOT pushed by a normal push
git push origin --tags                  # push all of them
git tag -d v0.1                         # delete a local tag
git push origin --delete v0.1           # delete it on the remote too
git describe --tags                     # "how far am I from the last tag?"

git describe prints something like v1.0-3-g2c7932c, meaning "three commits after v1.0, at commit 2c7932c". Build systems use it to stamp a version on every build.

Two cautions. A normal git push does not send tags, which is a common cause of "the release exists on my laptop only". And never move or reuse a tag that others have seen. If v1.0 means two different commits on two laptops, nobody can trust it. Tag v1.0.1 instead. GitHub's "Releases" page is built on tags.

4. Bisect: find the commit that broke it ​

Something worked last month. It is broken now. There are 200 commits in between. Which one did it?

You could read all 200. Or you could ask Git to bisect, which is a binary search through history. The idea is the same as guessing a number from 1 to 100 by asking "higher or lower?": you start at the middle, and each answer halves the remaining range.

Start: commit 1 is good, commit 12 is bad. Bug is somewhere between.123456789101112Test 1: commit 6 works. The bug is later.123456789101112Test 2: commit 9 is broken. The bug is at or before 9.123456789101112Tests 3 and 4 check 8 and 7. Commit 7 is the first bad one.
Git does not test all twelve commits. It tests the middle of the remaining range, and each answer throws away half. Twelve commits take four tests. A thousand would take ten.

You tell Git one commit that is good and one that is bad. Git checks out the middle one. You test it and say good or bad. Git halves the range and repeats.

text
$ git bisect start
$ git bisect bad                      # the current commit is broken
$ git bisect good HEAD~11             # this one, 11 commits ago, worked
Bisecting: 5 revisions left to test after this (roughly 3 steps)
[ab9c53c...] Change 6

Now test. If it works, type git bisect good; if not, git bisect bad. About four rounds later:

text
258427a6... is the first bad commit
commit 258427a6c736683265a3a4d13b10b7dce29385b8
    Change 7
 rate.ts | 2 +-

Git names the guilty commit. Then git bisect reset returns you to where you started.

Let Git run the test: bisect run ​

You can automate even that. Write a small script that exits with 0 when the code is good and a non-zero number when it is bad, and give it to Git:

text
$ cat check.sh
#!/bin/sh
grep -q "0.2;" rate.ts
$ git bisect run ./check.sh
running './check.sh'
Bisecting: 2 revisions left to test after this (roughly 2 steps)
running './check.sh'
running './check.sh'
running './check.sh'
258427a6c736683265a3a4d13b10b7dce29385b8 is the first bad commit
bisect found first bad commit
$ git bisect reset

Git checked out four different commits, ran the script on each, and reported the answer, with no help from you. Write the script, start it, and go get a coffee. Over 1,000 commits it needs about ten tests (because 2 to the power of 10 is 1,024).

The exit code 125 has a special meaning: "I cannot test this commit, skip it" (for example, it does not even build). Use git bisect skip for the manual version.

It works for slowness too. Make the script fail when a benchmark is slower than a limit, and bisect finds the commit that made the code slow. Chapter 15.6 puts this into the wider method of debugging.

Its one requirement is that individual commits are in a working state. If half your history does not build, bisect cannot tell good from bad. That is a real reason to keep commits small and complete (Chapter 13.11.1).

5. Searching history ​

Git remembers everything. These commands let you ask it questions.

"When did this text appear or disappear?" -S (the "pickaxe") finds commits that changed how many times a string appears.

text
$ git log --oneline -S"0.25"
258427a Change 7

Use -G"regex" instead when you want to match a pattern.

"What is the full history of these lines?" -L follows a range of lines (or a function) through every commit that touched it, and shows each change:

text
$ git log -L1,1:rate.ts --oneline
258427a Change 7
-export const RATE = 0.2;
+export const RATE = 0.25;
9efb719 Change 1
+export const RATE = 0.2;

"Who last changed this line, and why?" git blame prints each line of a file with the commit that last changed it.

text
$ git blame -L1,1 --date=short rate.ts
258427a6 (Ana Ruiz 2026-10-28 1) export const RATE = 0.25;

The name is unfortunate. You are not looking for someone to blame. You are looking for the commit message that explains the line. Two flags make it more useful: -w ignores whitespace-only changes, and -C follows lines that were moved or copied from another file. When a big "reformat everything" commit pollutes the results, list its id in a file named .git-blame-ignore-revs and use git blame --ignore-revs-file.

"Where in the code does this word occur?" git grep searches the tracked files, quickly, and can search an older version:

text
$ git grep -n "RATE"
rate.ts:1:export const RATE = 0.25;
$ git grep -n "RATE" HEAD~8
HEAD~8:rate.ts:1:export const RATE = 0.2;

More one-liners:

bash
git show HEAD~6:rate.ts                    # a file as it was in an older commit
git log --follow -- cart.ts                # history of a file, through renames
git log -- cart.ts                         # commits that touched a path
git log --diff-filter=D --summary          # find commits that deleted files
git shortlog -sn HEAD                      # who made how many commits

6. Worktrees: two branches, two folders, one repository ​

Back to the start of this page. Stash works, but there is another way to handle "urgent fix while I am busy": do not move your work at all. Open a second folder with the other branch.

The repository (.git)all commits, stored once~/shopbranch: mainyour feature work in progress~/hotfix-treebranch: hotfix-1a clean copy for the urgent fixgit worktree add ../hotfix-tree -b hotfix-1 main
A worktree is a second folder that shares the same repository. The history is stored once in .git. Each folder has a different branch checked out, so urgent work never forces you to put your current work away.
text
$ git worktree add ../hotfix-tree -b hotfix-1 main
Preparing worktree (new branch 'hotfix-1')
HEAD is now at 688585e Start the shop
$ git worktree list
/home/ana/shop         688585e [main]
/home/ana/hotfix-tree  688585e [hotfix-1]

git worktree add <folder> -b <new-branch> <start-point> creates the folder ../hotfix-tree, with a new branch hotfix-1 checked out in it. Your original folder is untouched, with all its half-finished work. You can open the second folder in a second editor window, fix the bug, commit and push, all without stashing anything.

Both folders use one repository. The history is stored once, so a worktree is cheap, and a commit made in one is instantly visible in the other. When the job is done:

bash
git worktree remove ../hotfix-tree
git worktree prune          # clean up records of folders you deleted by hand

One rule: a branch can be checked out in only one worktree at a time. Worktrees are also useful for running a long build or test on one branch while you carry on editing another.

7. A few more things you will meet ​

Stashes are commits. The stash is a stack of ordinary commits referenced from refs/stash, which is why a dropped stash can be recovered by its id.

Aliases shorten long commands. Put them in your config once:

bash
git config --global alias.lg "log --oneline --graph --all --decorate"
git config --global alias.st "status -sb"
text
$ git lg | head -4
* f4b319c (dev) Start next feature
* 15f28f4 Fix checkout rounding
| * e2039c3 (release/1.0) Fix checkout rounding
| * ab15a75 Release 1.0 marker

Renaming a branch that is already on the remote. Rename locally, push the new name, delete the old one:

bash
git branch -m old-name new-name
git push origin -u new-name
git push origin --delete old-name      # older Git: git push origin :old-name

Anyone else who had old-name must rename theirs too, or they will keep pushing the old one back.

Very large repositories. Cloning the full history of a huge project can take an hour. Git has three ways to help:

  • --depth 1 (a shallow clone) downloads only the latest commit. It is the right default on a build server.
  • Partial clone (--filter=blob:none) downloads the commits and folders at once, and fetches file contents on demand. A huge repository becomes usable immediately.
  • Sparse checkout (git sparse-checkout set path/to/folder) fills your working folder with only some directories. That is how a repository holding hundreds of projects stays workable.

Large binary files. Git handles text well and big binaries badly (Chapter 13.11.5). Git LFS keeps a small pointer in Git and stores the big file on a separate server. You choose which files with git lfs track "*.psd".

Submodules. A submodule pins another repository, at one exact commit, inside yours. They let a project include a library by reference rather than by copy.

bash
git submodule add git@github.com:acme/pricing-lib.git libs/pricing
git clone --recurse-submodules git@github.com:ana/shop.git
git submodule update --init           # fetch them after a plain clone

They are powerful and easy to get wrong. The parent repository records only the commit of the submodule, so teammates must update it deliberately, and forgetting is a common mistake. If you only need shared code, a package manager is usually simpler.

What the interviewer will push on ​

These questions show whether you have worked on a real team.

"You are halfway through a task and need to switch for an urgent fix. What do you do?" Several good answers: stash with -u and a message, or make a work-in-progress commit, or open a worktree. The better answer says why you chose one. Stash is quick; a WIP commit is safest because the reflog protects it; a worktree avoids moving anything. Mentioning -u for untracked files shows experience.

"What does git cherry-pick do, and when would you use it?" It copies one commit onto the current branch as a new commit. Use it to port a fix to a release branch without taking the rest of the work. Say -x records the origin. A weak answer forgets that the new commit has a different id.

"What is the difference between a lightweight and an annotated tag?" Lightweight is just a label on a commit. Annotated is a full object with tagger, date and message, and can be signed. Use annotated for releases. A good addition: tags are not pushed by default.

"How would you find which commit introduced a bug?" git bisect. Explain it as a binary search: about log base 2 of N tests. Add bisect run with a script to automate it. The deeper point: it requires every commit to build, which is a reason for small atomic commits.

"How do you find when a line of code was added, or who wrote it?" git blame for the last change, git log -S for when a string appeared, git log -L for a line's full history. Mention ignoring bulk formatting commits.

"What is a worktree?" A second checked-out folder sharing the same repository, so you can work on two branches at once with no stashing.

One thing to volunteer: mention git bisect run with a script that checks a performance threshold. It shows you use Git for debugging beyond "I found a bug", and almost nobody volunteers it.

Recall

  • Stash is a shelf for uncommitted work. git stash push -u -m "label" (the -u includes untracked files), list, show -p, pop (restore and remove), apply (restore and keep). A stash is not tied to a branch, and is built from ordinary commits.
  • git cherry-pick -x <id> copies one commit onto the current branch as a new commit with a new id; -x records the original. Right for porting a fix to a release branch; not a habit to avoid merging.
  • A tag is a label that never moves. Annotated tags (-a) are full objects with a tagger and message, can be signed, and are the right choice for releases; lightweight tags are just labels. A normal push does not send tags: use git push origin v1.0 or --tags. Name them with semantic versioning (MAJOR.MINOR.PATCH).
  • git bisect is a binary search for the commit that broke something, about log₂ N tests. git bisect run ./check.sh automates it (exit 0 = good, 125 = skip), and works for performance regressions. It needs every commit to build.
  • History search: git log -S"text" (when did it appear), -L start,end:file (history of lines), git blame -w -C (who last changed it), git grep (search tracked files, even in old commits), git log --follow.
  • git worktree add ../folder -b branch main gives a second working folder on the same repository, so urgent work needs no stashing. A branch can be checked out in only one worktree.
  • Big repositories: --depth 1, partial clone (--filter=blob:none), sparse checkout; Git LFS for large binaries; submodules pin another repository at one commit.

Self-test: Why use -u when stashing? · What is the difference between stash pop and stash apply? · What does git cherry-pick -x add to the commit message? · Why are tags not sent by a normal git push? · How many tests does bisect need for 1,000 commits, and why? · When is a worktree better than a stash?

Next: 13.11.8 takes everything from these seven pages into a team: pull requests and review, forks, protected branches, how teams organise their branches, and how to write the history others will read.

Combine chapters into one PDF

Pick the chapters you want. They print in the order you pick them.

Volume I — Technology
Part 0 — Retention & Notation
Part 1 — Foundations of Computation
Part 2 — Operating Systems
2.1 The Kernel
2.2 Processes
2.3 Threads & Scheduling
2.4 Concurrency Under the Hood
2.5 Memory Management
2.6 File Systems
2.7 Input/Output
2.8 Linux for Engineers
2.9 Windows & macOS in Practice
Part 3 — Languages, Compilers & Runtimes
3.6 JavaScript & V8
3.7 TypeScript
3.8 Node.js Internals
3.13 Python & CPython
3.14 FastAPI & Production Python
Part 4 — Data Structures & Algorithms
4.0 Classic Problems — Before NeetCode
4.4 Arrays & Hashing — Problems
4.5 Two Pointers
4.6 Sliding Window
4.8 Stack — Problems
4.9 Linked List — Problems
4.11 Binary Search — Problems
4.13 Trees
4.14 Tree — Problems
4.15 Trie — Problems
4.17 Heap — Problems
4.18 Backtracking — Problems
4.19 Graphs
4.20 Graph — Problems
4.21 Advanced Graph — Problems
4.23 1-D DP — Problems
4.24 2-D DP — Problems
4.26 Greedy — Problems
4.27 Interval — Problems
4.28 Math & Geometry — Problems
4.30 Bit Manipulation — Problems
Part 5 — Networking & the Web
5.3 IP
5.4 Transport
5.6 HTTP
Part 6 — Frontend Engineering
6.1 Browser Internals
6.2 HTML & CSS Mastery
6.3 JavaScript in the Browser
6.4 React, from First Component to Full Shop
6.5 Frameworks & Rendering
6.8 UI Engineering & Patterns
Part 7 — Databases & Storage
7.2 SQL Mastery
7.3 Storage Engine Internals
7.4 Transactions
7.5 NoSQL Taxonomy
7.8 Analytics & Big Data
Part 8 — Security, Identity & Cryptography
8.2 Cryptography
8.3 Protocols of Trust
8.4 Identity: AuthN & AuthZ
8.5 Application Security
8.6 Infrastructure Security
Part 9 — Software Design (LLD)
9.2 OOP Foundations
9.3 Design Principles
9.4 Design Patterns
9.5 Concurrency
9.6 API Design
9.7 LLD Interview Machines
9.9 Node/Express Production Playbook
Part 10 — Distributed Systems & HLD
10.7 Consistency & Consensus
10.8 Messaging & Microservices
10.14 Caching
Building blocks from the design seat
Part 11 — System Design Case Studies
Part 12 — AI & ML Engineering
12.1 What AI Engineering Is
12.2 The Math You Need
12.3 Classical Machine Learning
12.4 Data for ML
12.5 Deep Learning
12.6 Embeddings & Vector Search
12.7 Transformers & LLMs
12.8 Building with LLMs
12.9 Retrieval-Augmented Generation
12.10 Agents
12.11 Adapting Models
12.12 Production AI
12.13 Multimodal AI
12.14 AI Security & Governance
12.15 Case Studies & Capstone
Part 13 — Cloud, DevOps & Infrastructure
13.11 Git, from First Commit to Team Workflow
Part 14 — Containers: Docker & Kubernetes
14.1 Foundations
14.2 Docker
14.3 Kubernetes
14.4 Kubernetes on Azure
Part 15 — The Craft & Career
Nothing picked yet