Git Stash: Safely Managing Working Directory Changes During Branch Switches

Git Stash: Safely Managing Working Directory Changes During Branch Switches

ยท

2 min read

  1. 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
    

  2. Check that you have uncommitted changes:

     git status
    

  3. To stash your changes, you need to first add the files:

     git add newfile.txt existingfile.txt
    
  4. Stash your changes to save them temporarily:

     git stash
    

  5. 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.

  6. Make changes and commit the bug fix on the bugfix branch.

    1. Create a sample buggy file:

       echo "foo" > bugfix.txt
      

    2. Make the changes needed to fix the critical bug:

       sed 's/foo/bar/' bugfix.txt
      

      It should now contain "bar" instead of "foo".

    3. Add and Commit the changes:

       git add bugfix.txt
       git commit -m "Fix critical bug"
      

  7. Switch back to the original branch:

     git checkout master
    

  8. Apply the changes you had stashed:

     git stash apply
    

  9. 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!

ย