CodeBlanks Logo Icon CodeBlanks

git stash

Learn to temporarily save changes with git stash.

Clearing working tree with git stash

When you have unfinished work and need to switch branches or fix an urgent bug, you don't want to commit incomplete code. The git stash command shelves both working tree and staged changes into a temporary storage stack. Your working directory then returns to the clean state of the latest commit (HEAD).

git status
git stash

You can later restore these shelved changes and continue developing right where you left off.

Stash with message and untracked files

By default, git stash only saves changes made to tracked files. If you also want to stash newly created untracked files, add the -u flag. You can provide a custom description using push -m to remember what each stash entry contains.

git stash -u
git stash push -m "login form development"

Leaving descriptive messages makes life much easier, especially when multiple stash entries accumulate.

Practice Clean working tree with stash

Shelve unfinished changes in app.py using git stash -q, and then print that the file returned to its original state using cat app.py.

Starter code

terminal
git init -q
git config user.name "Canan"
git config user.email "canan@example.com"
echo "surum 1" > app.py
git add app.py
git commit -qm "Ilk commit"
echo "surum 2 calismasi" >> app.py

# Degisiklikleri stash'e al ve dosya icerigini yazdir

Sample solution

terminal
git init -q
git config user.name "Canan"
git config user.email "canan@example.com"
echo "surum 1" > app.py
git add app.py
git commit -qm "Ilk commit"
echo "surum 2 calismasi" >> app.py

git stash -q
cat app.py

Expected output

surum 1

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What happens to unsaved changes in the working tree when git stash is run?

  • They are automatically added to the repo as a permanent commit
  • They are shelved to a temporary stack and working tree returns to HEAD Correct answer
  • Only newly created files are removed from the working tree
  • They are permanently deleted and cannot be recovered

Explanation: git stash shelves changes not yet ready to commit into a temporary stack and cleans the working tree.

2 Include untracked files in stash

Question
git stash ____
Answer
git stash -u

Explanation: The -u (or --include-untracked) option includes new untracked files in the stash stack.

3 Stash fundamentals

Term Meaning
git stash Shelves changes to temporary stack
-u Also stashes untracked files
git stash push -m Adds description message to stash
Temiz çalışma alanı Returns to HEAD once changes stashed

All lessons in Intermediate

20 Intermediate final

  1. Branch management
  2. Rebase
  3. Conflict
  4. PR flow