Git Stash: Safely Managing Working Directory Changes During Branch Switches
Make some changes in your working directory on the current branch (e.g. main). For example:
# Add a new file touch newfile.txt # Make changes to an existing file echo "Some changes" >> existingfile.txt
Check that you have uncommitted changes:
To stash your changes, you need to first add the files:
git add newfile.txt existingfile.txt
Stash your changes to save them temporarily:
Switch to another branch to fix a critical bug, e.g.:
git checkout -b bugfix-branch
The -b flag tells git to create the branch if it doesn't already exist.
Make changes and commit the bug fix on the bugfix branch.
Create a sample buggy file:
echo "foo" > bugfix.txt
Make the changes needed to fix the critical bug:
sed 's/foo/bar/' bugfix.txt
It should now contain "bar" instead of "foo".
Add and Commit the changes:
git add bugfix.txt git commit -m "Fix critical bug"
Switch back to the original branch:
git checkout master
Apply the changes you had stashed:
git stash apply
Commit them as usual:
git add . git commit -m "My original changes"
So in summary, you can use git stash to temporarily save your work, switch branches to fix bugs, and then re-apply the stashed work.
Did you find this article valuable?
Support Edvin Dsouza by becoming a sponsor. Any amount is appreciated!