1. Home
  2. Blog
  3. DevOps

DevOps

Git Stash Explained: Save, Apply, Pop and Untracked Files, Tested

Git stash puts your unfinished changes on a shelf so you can switch tasks with a clean working tree, then bring them back later. Learn every everyday stash command, what each one really keeps, and how to recover from conflicts, with output we ran on Git 2.56.

9 min read
Git stash explained: save, apply, pop and untracked files

Key takeaways

  • Git stash saves tracked changes and staged changes, then resets your working tree to the last commit.
  • Untracked files are left behind unless you add -u; in our test, todo.txt stayed in place after a plain stash.
  • apply keeps the stash entry and pop deletes it, except after a conflict, when Git kept the entry for safety.
  • git stash branch turns a stash into a new branch and is the cleanest escape from a conflicting pop.

You are halfway through a feature when an urgent bug report lands. Your changes are not ready to commit, but you need a clean branch now. Git stash is built for this moment: it records your work in progress, cleans your working directory, and lets you restore everything later, on the same branch or a different one.

We ran every command below on Git 2.56 in a throwaway repository, using a demo identity so no personal details appear. The outputs are copied from that run. If you are still learning the basics of commits and branches, start with our Git tutorial for beginners.

What is git stash?

git stash takes the changes in your working tree and index (the staging area), saves them as special commits on a stack, and resets your files to match HEAD. Stashes are local: they are never pushed to a remote. Each entry gets a name such as stash@{0}, where 0 is always the newest.

Under the hood, a stash entry is a small merge commit: one parent is your HEAD, another records the index, and an optional third records untracked files. That is why stashes survive restarts and can be inspected like any other commit.

Our test repository

We committed one file, then created three kinds of change: a modified tracked file, a new staged file and a new untracked file:

$ git status --short
 M app.txt
A  staged.txt
?? todo.txt

The left column shows the index and the right shows the working tree. M is modified, A is added to the index and ?? is untracked.

Stashing changes with a message

The modern form is git stash push. Always add a message with -m; “WIP on main” tells you nothing a week later.

$ git stash push -m "wip: price field"
Saved working directory and index state On main: wip: price field

$ git status --short
?? todo.txt

Both the modified app.txt and the staged staged.txt disappeared into the stash. The untracked todo.txt did not. Plain git stash with no arguments does the same as push without a message.

Stashing untracked files

New files that Git has never tracked are ignored by default. Add -u (--include-untracked) to take them too:

$ git stash push -u -m "wip: todo"
Saved working directory and index state On main: wip: todo

$ git status --short
(nothing: the working tree is clean)

Use -a (--all) only if you also want ignored files, such as build output, which is rarely what you mean. To stash only some files, list them after --, for example git stash push -m "css" -- styles.css, or use -p to choose hunks interactively.

Tip: forgetting -u is the most common stash surprise. The new file stays behind, follows you to the other branch, and may even be committed there by accident.

Listing and inspecting stashes

We now had two entries. The newest is always stash@{0}, so older entries shift up by one every time you stash again:

$ git stash list
stash@{0}: On main: wip: todo
stash@{1}: On main: wip: price field

To see what a stash contains before restoring it, use show. Add -p for the full diff:

$ git stash show -p stash@{1}
diff --git a/app.txt b/app.txt
--- a/app.txt
+++ b/app.txt
@@ -1 +1,2 @@
 title = "Shop"
+price = 10
diff --git a/staged.txt b/staged.txt
new file mode 100644
+staged line

By default show ignores the untracked part. For the second stash, git stash show --include-untracked --stat stash@{0} listed todo.txt | 1 +, which confirms the file really was saved.

git stash apply vs git stash pop

Both commands restore a stash. The difference is what happens to the entry afterwards:

$ git stash apply stash@{1}
$ git stash list
stash@{0}: On main: wip: todo
stash@{1}: On main: wip: price field      (still there)

$ git stash pop --index stash@{1}
Dropped stash@{1} (7899bba...)
$ git stash list
stash@{0}: On main: wip: todo
Command Restores changes Removes the entry Best for
git stash apply Yes No Applying the same changes to several branches, or playing safe
git stash pop Yes Yes, if no conflict Everyday “put it back” use

Without a name, both use stash@{0}. When you have several stashes, name the one you want; popping the wrong entry onto the wrong branch is easy.

Keeping staged changes staged

By default a restore puts modified files back as unstaged changes, so your careful staging is lost. Add --index to restore the staging area as it was. In our run, the new file came back staged either way. For a modified file that was partly staged (status MM), a plain pop came back as M, with the staging lost, while pop --index restored MM exactly. A related option, git stash push --keep-index, stashes everything but leaves the staged changes in place, which is handy for testing exactly what you are about to commit.

When pop hits a conflict

If the branch changed the same lines since you stashed, restoring causes a conflict. We stashed a title change, then committed a different title, then popped:

$ git stash pop
Auto-merging app.txt
CONFLICT (content): Merge conflict in app.txt
The stash entry is kept in case you need it again.

$ git status --short
UU app.txt

Git refused to drop the entry because the restore did not finish cleanly. Resolve the conflict markers as you would after a merge, stage the file, and then run git stash drop yourself once you are happy. If you would rather abandon the attempt, git checkout -- . or git reset --hard returns to the commit; the stash is still safe. Our merge vs rebase guide covers conflict resolution in more depth.

Turning a stash into a branch

When a stash no longer applies cleanly, create a branch from the commit where you made it:

$ git stash branch rename-fix stash@{0}
Switched to a new branch 'rename-fix'
Changes not staged for commit:
        modified:   app.txt
Dropped stash@{0} (900b8b7...)

Because the new branch starts at the original base commit, the changes apply without conflict. Commit them there and merge or rebase later. This is also the best move when a “quick stash” turns into real work that deserves its own branch.

Dropping and clearing stashes

$ git stash drop stash@{0}
Dropped stash@{0} (17ef58b...)
$ git stash clear
$ git stash list
(empty)

drop removes one entry and clear removes them all, with no confirmation. If you drop something by mistake, the hash printed by drop can still restore it for a while with git stash apply <hash>, until Git’s garbage collection removes unreachable objects. Copy that hash before closing the terminal. For other undo tools, see our git reset vs revert guide.

Good stash habits

  • Keep the stack short. More than two or three entries usually means work that belongs on a branch.
  • Always use messages. They are the only clue to what an entry holds.
  • Check before you pop. Run git stash show -p and confirm the current branch.
  • Prefer a commit for long breaks. A work-in-progress commit on a feature branch is backed up when you push; a stash is not.
  • Consider worktrees. git worktree add gives you a second checkout for urgent fixes with no stashing at all.

Git stash cheat sheet

Goal Command
Stash with a message git stash push -m "msg"
Include untracked files git stash push -u
Stash specific files git stash push -- path
List stashes git stash list
Show a stash’s diff git stash show -p stash@{n}
Restore and keep git stash apply stash@{n}
Restore and remove git stash pop stash@{n}
Restore staging too git stash pop --index
Stash into a new branch git stash branch name stash@{n}
Delete one or all git stash drop, git stash clear

Final thoughts

Git stash is the fastest way to set work aside, as long as you remember what it does and does not keep. Name every stash, add -u for new files, inspect before you restore, prefer apply when unsure, and reach for git stash branch when a restore fights back. For the rest of your daily commands, keep our Git commands cheat sheet close.

Frequently asked questions

What does git stash do?

It saves your uncommitted tracked and staged changes on a local stack and resets the working tree to the last commit, so you can switch tasks and restore the changes later.

What is the difference between git stash pop and apply?

Both restore the changes. pop also deletes the stash entry when it applies cleanly, while apply keeps the entry so it can be reused or kept as a backup.

Does git stash include untracked files?

No, not by default. Use git stash push -u or –include-untracked to stash new untracked files, and -a to include ignored files too.

How do I recover a dropped stash?

Use the commit hash that git stash drop printed with git stash apply followed by the hash. It works until garbage collection removes the unreachable commit.

Are stashes pushed to the remote repository?

No. Stashes exist only in your local repository. Commit work to a branch and push it if you need a backup or want to share it.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

BM25 Explained: How Keyword Search Ranks Results, With Python Code and Hybrid Search

BM25 explained with a pure Python implementation we ran: the formula, IDF, term saturation, the k1 and b parameters, why…

Read article →
Software Development

HTTP Methods Explained: GET, POST, PUT, PATCH, DELETE, Tested on a Live Server

HTTP methods explained with a small server we ran: GET, POST, PUT, PATCH, DELETE, HEAD and OPTIONS, safe vs idempotent,…

Read article →
DevOps

Git Bisect Explained: Find the Commit That Broke Your Code, Manually or Automatically

Git bisect explained with a tested repository: find the one bad commit among 41 in 5 test runs, automate it…

Read article →
Test Automation

pytest Markers Explained: Custom Marks, skip, skipif, xfail and -m Filters

pytest markers explained with a tested suite: register custom marks, run only smoke tests with -m, combine filters with and,…

Read article →
Software Testing

Positive vs Negative Testing: Differences, 24 Real Test Cases and a Checklist

Positive vs negative testing explained with a real signup form: 6 positive and 18 negative test cases run in pytest,…

Read article →
Databases & SQL

SQL ORDER BY Multiple Columns: ASC, DESC, NULLS LAST, Case and Custom Order

SQL ORDER BY with multiple columns explained with tested queries: mixed ASC and DESC, tie-breakers, NULLS FIRST and LAST, case-insensitive…

Read article →
Databases & SQL

SQL Running Total: SUM OVER, Per-Group Totals, Moving Sums and the RANGE Trap

How to calculate a SQL running total with SUM() OVER: per-group totals, daily cumulative sums, moving sums, percent of total,…

Read article →
Software Development

JavaScript Sort Array: Numbers, Objects, Strings and Why 10 Comes Before 5

How to sort an array in JavaScript correctly: numbers with a compare function, objects by one or more fields, strings…

Read article →
Software Development

Python String Methods: Cheat Sheet, Real Examples and the strip() Trap

Python string methods with tested examples: split, join, strip, replace, find, startswith, is-methods, casefold, partition and translate, plus the strip()…

Read article →
Software Development

Python zip() Explained: Loop Two Lists at Once, Unzip, strict=True and Traps

Python zip() pairs items from several lists in one loop. Tested examples for dicts, unzipping with *, strict=True, zip_longest, sliding…

Read article →
Artificial Intelligence

Cosine Similarity Explained: Formula, Worked Example and Python Code

Cosine similarity explained simply: the formula, a worked example by hand, pure Python and NumPy code, cosine vs Euclidean distance…

Read article →
Software Development

UTF-8 Encoding Explained: How Text Becomes Bytes and How to Fix Garbled Text

UTF-8 encoding explained with byte-level examples we ran in Python: how characters become 1 to 4 bytes, why café turns…

Read article →
DevOps

Git Squash Commits: 4 Easy Ways, Tested Step by Step (rebase -i, reset, merge)

Git squash commits explained with 4 tested methods: interactive rebase, reset –soft, merge –squash and fixup with autosquash. Before-and-after logs,…

Read article →
Test Automation

pytest parametrize Explained: 7 Patterns with Tested Examples

pytest parametrize explained with 7 tested patterns: basic cases, readable ids, stacked decorators, pytest.param with xfail and skip, indirect fixtures…

Read article →
Software Testing

Retesting vs Regression Testing: 8 Key Differences with a Real Bug Fix Example

Retesting vs regression testing explained with a real bug fix run in pytest: retesting confirmed the fix, the regression run…

Read article →
Databases & SQL

Delete Duplicate Rows in SQL: 5 Safe Methods, Tested Step by Step

How to delete duplicate rows in SQL safely: find them, preview them, then remove them with ROW_NUMBER, MIN(id), EXISTS, rowid…

Read article →
Databases & SQL

SQL RANK vs DENSE_RANK vs ROW_NUMBER: Differences with Tested Examples

SQL RANK vs DENSE_RANK vs ROW_NUMBER in one table: how each handles ties, top-N per group, the second-highest salary trap…

Read article →
Software Development

JavaScript Optional Chaining (?.) Explained: 8 Examples, ?? Defaults and Traps

JavaScript optional chaining stops “Cannot read properties of undefined” errors. 8 tested examples for properties, arrays and methods, ?? vs…

Read article →
Artificial Intelligence

RAG Chunking Strategies Explained: Fixed, Overlap, Sentence, Recursive and Headings, Measured

RAG chunking strategies compared on one document with tiktoken 0.14: fixed-size, overlap, sentence packing, recursive splitting and heading-based chunks, measuring…

Read article →
DevOps

Git Stash Explained: Save, Apply, Pop and Untracked Files, Tested

Git stash explained with commands we ran on Git 2.56: push with a message, untracked files, list and show, apply…

Read article →
Software Testing

Pairwise Testing Explained: How All-Pairs Cuts 216 Tests to 13, Tested

Pairwise testing explained with a generator we ran in Python 3.13: a checkout with 216 combinations covered by 13 tests,…

Read article →
Test Automation

Test Doubles Explained: Dummy, Stub, Spy, Mock and Fake, with Tested Python Code

Test doubles explained with one Python example run in pytest 9.2: dummy, stub, spy, mock and fake, when to use…

Read article →
Databases & SQL

SQL COALESCE Explained: Defaults, NULLIF, IFNULL vs ISNULL and Traps, Tested

SQL COALESCE explained with queries we ran in SQLite 3.50: first non-null values, empty strings, NULL in maths, NULLIF for…

Read article →
Databases & SQL

SQL Self Join Explained: Employee-Manager, Pairs and Row Comparisons, Tested

SQL self join explained with queries we ran in SQLite 3.50: employee and manager, earning more than the manager, unique…

Read article →
Artificial Intelligence

LLM Context Window Explained: Tokens, Limits and How to Fit More, Measured

The LLM context window explained with token counts we measured using tiktoken: words vs tokens for prose, code and Hindi,…

Read article →
DevOps

Git Cherry-Pick Explained: Copy the Commit You Need, Safely, Tested

Git cherry-pick explained with commands we ran in Git 2.56: copying a hotfix to a release branch, new hashes and…

Read article →
Test Automation

Snapshot Testing Explained: How It Works, When It Helps and When It Hurts

Snapshot testing explained with a pytest and syrupy demo we ran: creating snapshots, reading the diff after a code change,…

Read article →
Software Testing

Mutation Testing Explained: Why 100% Coverage Still Missed Our Bug

Mutation testing explained with a small mutation tool we built and ran: 14 mutants, a test suite with 100% line…

Read article →
Artificial Intelligence

Prompt Injection Explained: How AI Apps Get Tricked and How to Defend Them

Prompt injection explained for builders: direct and indirect attacks, why keyword filters fail (our test blocked 1 of 4), and…

Read article →
DevOps

DNS Records Explained: A, AAAA, CNAME, MX, TXT and TTL With Real Lookups

DNS records explained with lookups we ran: how resolution works, A and AAAA, CNAME rules, MX and null MX, TXT…

Read article →
DevOps

Feature Flags Explained: Safe Releases, Gradual Rollouts and Flag Hygiene

Feature flags explained with a rollout simulation we ran: flag types, percentage rollouts with stable hashing, kill switches, allow lists,…

Read article →
Test Automation

Test Data Generation With Python Faker: Realistic, Repeatable and Safe Data

Test data generation with Python Faker, run and measured: seeding for repeatable data, locales, unique values, domain-shaped records, edge cases…

Read article →
Software Testing

Shift-Left Testing Explained: Find Bugs Earlier Without Slowing the Team

Shift-left testing explained: what it means, why early defects are cheaper, practices from requirement reviews to CI checks, the tester's…

Read article →
Artificial Intelligence

LLM Structured Output Explained: Getting Reliable JSON From AI Models

LLM structured output explained with validation we ran in Pydantic: JSON mode and schemas, constrained decoding, the ways model output…

Read article →
Test Automation

API Contract Testing Explained: Catch Breaking Changes Before They Ship

API contract testing explained with a schema check we ran: what a contract is, consumer-driven contracts, Pact, OpenAPI, which changes…

Read article →
Software Testing

Risk-Based Testing Explained: Score Risks, Build a Matrix and Test What Matters

Risk-based testing explained step by step: identifying risks, scoring likelihood and impact, building a risk matrix, mapping risk to test…

Read article →