Assume you are on a Branch and there is a need to switch to another branch. Why would you need to move to another branch? Here are some reasons:
There is a Development Env bug that you need to quickly look at.
A Production hotfix should go right away.
Or a urgent code review where you need to pull & switch to another branch
Or just someone asked you to check something on a different branch
You can do this in a couple of ways
Commit your changes. (May take more time)
Git Stash.
Git Stash
Git stash
is a useful Git command that temporarily stashes changes you've made to your working directory so you can work on something else. Later you can come back and re-apply your stashed changes.
Here are some common commands and usages for git stash
Stashing Changes
git stash
: Stash the changes in your working directory. This command temporarily stores all modified tracked files.git stash save [message]
: Same asgit stash
, but allows you to add a descriptive message to the stash for easy identification.
Listing All Stashes
git stash list
: Lists all stashed changes. Stashes are stored in a stack and can be listed to see all.
Viewing Stash Contents
git stash show
: Shows the changes recorded previously in the stash as a diff between the stashed changes & the original state.git stash show stash@{n}
: Show the changes in the specified stash.
Applying Stashed Changes
git stash apply
: Re-apply the changes stored in the latest stash.git stash apply stash@{n}
: Apply the changes from the specified stash.
Removing a Stash
git stash drop stash@{n}
: Remove a single stash entry from the list of stashes.git stash clear
: Remove all the stashed entries.
Here is how to make it work (For Please play with a temporary repository):
You are on some branch and you have some changes done but not committed and now you need to switch to another branch:
git status // To see what all you are working on.
git stash // Save your current changes into the stash.
git checkout ... // to another branch and complete your work.
git stash list // To see what stashed I've.
git stash apply // To apply the latest stashed code.