Git: Switching Tasks Without Losing Work
You’re deep into developing a cool new feature, and suddenly, a big bug needs fixing right now in the same repo. What can you do?
Linas Kapočius
Solutions Architect at Corgineering.com
One of the possible approaches would be to:
1️⃣ Commit your current changes
2️⃣ Switch to main/master branch and fetch all needed changes
3️⃣ Create a bugfix branch
But that could lead to 𝐩𝐫𝐨𝐛𝐥𝐞𝐦𝐬 like:
❌ 𝗘𝘅𝘁𝗿𝗮 "𝗡𝗼𝗶𝘀𝗲" 𝗶𝗻 𝗖𝗼𝗺𝗺𝗶𝘁 𝗛𝗶𝘀𝘁𝗼𝗿𝘆
By commiting half-finished work before switching to fix the bug, you'll eventually need to go back and amend the commit, squash it, or make additional "fixup" commits.
❌ 𝗣𝗼𝘁𝗲𝗻𝘁𝗶𝗮𝗹 𝗥𝗲𝗯𝗮𝘀𝗲 𝗼𝗿 𝗠𝗲𝗿𝗴𝗲 𝗖𝗼𝗻𝗳𝗹𝗶𝗰𝘁𝘀 𝗟𝗮𝘁𝗲𝗿
If feature work includes refactoring or major changes, switching branches can lead to conflicts when merging the bugfix later on.
So instead of committing incomplete work, git stash comes to the rescue! It lets you save your current changes without affecting the commit history. Here’s how to use it:
🔹 𝐒𝐭𝐞𝐩 𝟏: 𝐒𝐚𝐯𝐞 𝐲𝐨𝐮𝐫 𝐰𝐨𝐫𝐤 𝐰𝐢𝐭𝐡 𝐠𝐢𝐭 𝐬𝐭𝐚𝐬𝐡
git stash
or even naming it for clarity:
git stash save "WIP: adding additional ingestion endpoint"
Now your changes are safely stored, and you can switch branches without losing anything.
🔹 𝐒𝐭𝐞𝐩 𝟐: 𝐒𝐰𝐢𝐭𝐜𝐡 𝐛𝐫𝐚𝐧𝐜𝐡𝐞𝐬 𝐚𝐧𝐝 𝐟𝐢𝐱 𝐭𝐡𝐞 𝐛𝐮𝐠
git checkout main
git pull origin main
git checkout -b bugfix/branch
Go ahead and fix the bug! Once it’s done, commit and push your changes.
🔹 𝐒𝐭𝐞𝐩 𝟑: 𝐁𝐫𝐢𝐧𝐠 𝐛𝐚𝐜𝐤 𝐲𝐨𝐮𝐫 𝐟𝐞𝐚𝐭𝐮𝐫𝐞 𝐰𝐨𝐫𝐤 𝐰𝐢𝐭𝐡 𝐠𝐢𝐭 𝐬𝐭𝐚𝐬𝐡 𝐩𝐨𝐩:
git stash pop
After the bugfix is complete, simply pop your changes back into your working directory. It’s like you never left your feature work!
𝐁𝐨𝐧𝐮𝐬 𝐓𝐢𝐩𝐬 💡
🔸 Keep track of all stashed work with this command.:
git stash list
Example output:
git stash apply
or
git stash apply stash@{1}
This article is part of our Best Practices series. Check out our other articles.