Challenge 005 - Recover changes with stash
Scenario
You are in the middle of a feature, with unfinished changes in your working directory, when you get word of an urgent production bug that has to be fixed on main right away. You do not want to commit incomplete code. Your goal is to temporarily save your work, switch branches, fix the bug, and then recover your work right where you left off.
How to solve it
# You are on feature with half-done changes (not committed)
git status
# Changes not staged for commit: archivo.js (a medias)
# 1. Save the changes temporarily and clean the working directory
git stash push -m "feature a medias"
# The working directory becomes clean, as at the last commit
# 2. Switch to main to handle the urgent bug
git switch main
echo "fix aplicado" > hotfix.txt
git add hotfix.txt
git commit -m "fix: corrige bug critico en produccion"
git push
# 3. Go back to the feature branch
git switch feature
# 4. Recover the saved changes
git stash pop
# Your half-done changes come back and the stash is removed from the stack
Why it works
git stash takes your uncommitted changes and saves them on a separate stack, leaving the working directory clean so you can switch branches without conflicts. After resolving the urgent issue, git stash pop reapplies those changes onto your branch and deletes the stash from the stack. This way you switch context without committing incomplete code or losing work.
Full solution
View commented solution
# Save (with a message to identify it). Use -u if you have new files.
git stash push -m "feature a medias"
# If you had untracked files: git stash push -u -m "feature a medias"
# View the stack of stashes
git stash list
# stash@{0}: On feature: feature a medias
# Handle the bug on main
git switch main
# ...fix, commit, push...
# Go back and recover
git switch feature
git stash pop
# Recovers and deletes the stash. If you wanted to keep it: git stash apply
# Verify that your changes came back
git status
# Changes not staged for commit: archivo.js (tu trabajo esta de vuelta)
Key point: pop recovers and deletes the stash; apply recovers but keeps it on the stack. And remember that git stash does not include untracked files unless you use -u.