Git Stash
Context
I’ve been working on a repository, which has branches that are different projects. So I forgot and began working on the main branch of a particular project instead of working on my branch for that project. After implementing a few features, I checked and realised that I was working on the wrong branch.
Problem: I need to transfer the code that I have written to the correct branch.
Avoid: Repetition of writing all the code again from scratch.
Solution: git stash
Why do I have to use git stash?
Git has an area called the stash where you can temporarily store a snapshot of your changes without committing them to the repository. It’s separate from the working directory, the staging area, or the repository. This functionality is useful when you’ve made changes to a branch that you aren’t ready to commit, but you need to switch to another branch.
You can create a stash by running: git stash
To see your stashes, run: git stash list
This will display all the stashes that you have. The latest stash you created will be in the position 0 and the older ones with incrementing index.
So, to solve my problem, I must run git stash on the wrong branch so that I can save my uncommitted changes temporarily. Then I will switch to the correct branch where my work should be. From there, I should recover my code from the stash I have created.
Retrieving code from the stash:
Run: git stash apply 0
0 represents the latest stash I have created, and it has the code I want to recover. If you saved your stash with a name, run; git stash apply name
After running the command, I got conflicts which I solved. In this way, I was able to transfer the code to the correct branch without the need of writing the code all over again using git stash.
For more resources on how to use git stash, below are my resources I used to educate myself on this topic.
Resources used: Git documentation, FreeCodeCamp
Update
When you have commited your code, and you want to that particular commit to another branch, use git cherry-pick