about:benjie

Random learnings and other thoughts from an unashamed geek

My Favourite Git Commands IV: Cleaning Up

| Comments

This is part 4 in my Favourite Git Commands series.

Cleaning up

Whether you want to do a quick bugfix in a different branch or just get rid of all your debugging, keeping your working directory clean is a good idea. Another way to do this is to use git reset --patch from part 1.

git stash

The stash is where you can store local modifications which you can then restore later.

Quickfix in other branch

If you need to hop to another branch but you’re in the middle of something then this type of thing works great:

git stash                # Save all local changes to stash
git checkout release     # Switch to branch needing quick fix
# Perform fix here
git commit               # Commit the fix to the release branch
git checkout feature     # Return to the feature branch you were on
git stash apply          # Re-apply the changes that you saved to stash
git stash drop           # If the above went well, tidy up

Testing staged changes

If you have a lot of changes in your working copy that you don’t want to commit (e.g. debugging) but you want to test your staged changes then you can do the following:

git stash --keep-index   # Remember index===staging area
# Perform tests here
git stash pop            # apply/drop all in one

If you’re planning to keep the changes on the stash for longer then I’d advise you to use git stash apply followed by git stash drop over git stash pop as if the apply fails you still have your original changes in the stash and it’s easier to resolve.

git reset --hard HEAD

This will clear out your staging area and working copy, checking out a fresh copy of HEAD. Use with caution as it does not store the work that is discarded. git reset --hard HEAD^ will do the same, but will also throw away your top commit on the current branch as well.

git stash; git stash drop

This is similar to the above, but it actually stores the code into git’s local files (before deleting the reference) so it is ever-so-slightly safer. Note this will be lost when git next does garbage collection.

Comments