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

Jaccard Similarity: Formula, Python, MinHash

Jaccard similarity measures overlap between two sets as intersection over union. Work the formula, compute it in Python for words…

Read article →
Software Development

Unix Timestamp Explained: Seconds vs ms

A Unix timestamp counts seconds since 1 January 1970 UTC. Learn seconds vs milliseconds, converting in Python, JavaScript and SQL,…

Read article →
DevOps

Git Hooks: Pre-commit and Commit-msg Examples

Git hooks run scripts at key moments such as commit and push. See tested pre-commit, commit-msg and prepare-commit-msg hooks, sharing…

Read article →
Test Automation

API Testing in Python: Pytest + Requests Suite

Build an API testing suite in Python with pytest and requests: fixtures, status codes, headers, JSON schema validation, CRUD flows,…

Read article →
Software Testing

Test Design Techniques: 9 Methods + Examples

Test design techniques help you write fewer tests that catch more bugs. Learn 9 black-box, white-box and experience-based methods with…

Read article →
Databases & SQL

SQL Temporary Table: Create, Use and Drop It

SQL temporary tables store interim results for one session. Learn syntax for SQL Server, PostgreSQL, MySQL, Oracle and SQLite, session…

Read article →
Databases & SQL

SQL CROSS JOIN: Every Combination + Examples

SQL CROSS JOIN returns every combination of rows from two tables. See the row math, product variants, calendar grids that…

Read article →
Software Development

JavaScript Date: Format, Parse, Timezone Bugs

JavaScript Date explained with tested Node.js code: zero-based months, the date-only UTC parsing trap, toISOString, getTimezoneOffset, Intl formatting, date math…

Read article →
Software Development

Python Requests: GET, POST, Timeouts, Retries

Python requests explained with code tested against a local API: GET with params, POST json vs data, headers and auth,…

Read article →
Software Development

Python Deepcopy vs Copy: Fix Nested Lists

Python deepcopy vs shallow copy explained with tested code: aliasing, nested lists, the [[0]*3]*3 trap, memo and cycles, custom __deepcopy__,…

Read article →
Artificial Intelligence

TF-IDF Explained: Formula and Worked Example

TF-IDF scores a word by how often it appears in a document and how rare it is across all documents….

Read article →
Software Development

Base64 Encoding Explained, With Python Code

Base64 encoding turns bytes into 64 safe text characters. See the bit-level steps, padding, URL-safe base64, the 33% size cost,…

Read article →
DevOps

Git Tag: Create, Push and Delete Release Tags

Git tag explained with tested commands: annotated vs lightweight tags, listing and sorting, pushing with follow-tags, deleting local and remote…

Read article →
Test Automation

Pytest Coverage: pytest-cov and Branch Gaps

Measure pytest coverage with pytest-cov: term-missing reports, branch coverage, HTML reports, pyproject settings and a fail-under gate for CI, with…

Read article →
Software Testing

Error Guessing in Testing: Checklist + Demo

Error guessing uses tester experience to predict where code breaks. Get a ready checklist of risky inputs, a step by…

Read article →
Databases & SQL

SQL LAG and LEAD: Compare Rows, 5 Examples

SQL LAG and LEAD read values from the previous or next row without a self join. Five tested examples: change,…

Read article →
Databases & SQL

SQL STRING_AGG: Combine Rows Into One String

SQL STRING_AGG joins values from many rows into one string per group. See syntax for PostgreSQL, SQL Server, MySQL GROUP_CONCAT,…

Read article →
Software Development

JavaScript Classes: Private Fields and Extends

JavaScript classes explained with tested Node.js code: constructors, methods, #private fields, getters, static members, extends and super, plus the errors…

Read article →
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 →
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 →
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 →
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 →
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 →
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 →