2018-08-26
|~3 min read
|549 words
I got into a bit of a mess earlier today when I accidentally checked out an old state of my current branch without creating a new branch for it. This resulted in a detached HEAD
state.
Among other problems, this meant that when I looked at my history, it was just the initial commit (which was the hash a5c779c
that I’d checked out).
I was able to recover the work because the past changes had been saved in my .git
directory, but in order to recover them, I had to checkout that directory by name since it wasn’t part of the current stream.
This was a scary moment, so I went about looking for a better way of doing things.
After reading several answers and articles on stackoverflow, medium, and other sites, the general approach I’ve seen boils down to a few steps that leverages branches — and thereby avoids the detached HEAD
state.
Here are the steps:
Create a new branch for the new feature that I want to work on
git checkout <new branch name>
Make your changes to the branch
Follow the standard workflow of tracking status $ git status
, adding files for tracking $ git add [file name]
, committing those changes with a message $ git commit -m "[message for commit]"
.
When you’re ready to merge the branch into your master
, check out the master, $ git checkout master
to return to the master branch
[When working on a team where the master may have changed] Make sure that the master
is up to date:
git pull origin master
Merge the new branch into the master
with $ git merge <new branch name>
Now that the files are merged, you can delete old branches. One quick way to see what’s already been merged (and therefore ready to be deleted is $ git branch --merged
.
Once a branch has been merged, it can be safe to delete it. To do so, use $ git branch -d [branch name]
(the -D
flag is a force delete).
Now, make sure that nothing hasn’t yet been merged which should be using $ git branch --no-merge
Though these steps are a faithful reproduction of my process, the way I really got more comfortable was by creating a test repo and testing all of this out. Making frequent use of $ git log
, $ git branch
, and $ git status
.
Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!