Sometimes in the middle of software development, you want to try some crazy idea out but don't want to mess up with current code. What should you do?
Let's say I'm developing a website. The current text color of the main tag is red, as shown here:
main {
color: red;
}
Currently, this is the whole git history:
What if I want to try using color blue for main instead?
Instead of creating a new branch, I can checkout the branch where I want to start the experiment. In this example, I'm going to checkout the latest branch.
git warns me about what I did. HEAD is not pointing to any branch now and it's in "detached" mode.
What's special about this mode? Here are some:
Now, let's try changing the text color to blue and commit the change.
Let's say I'm done with the experiment. If I don't like the new color, I can just checkout other branch and forget about changes I made in detached HEAD mode. They will be garbage collected.
However, if I like the changes. I can start a new branch from existing code in detached HEAD mode. Now, the changes are persisted in the new branch. Creating a new branch in the detached HEAD mode is simple. In the code below, I create a new branch with a name "bluetext"
git branch bluetext
Now, if I checkout other branch (master) and then checking back to blue text, all changes I made in the detached HEAD mode are there.
I find this trick is quite useful when I want to test out new ideas or small features. I can skip the work of creating new branch. Also, if the idea doesn't work, I can just leave it there and let the garbage collector do its job.