Branches in Git
Branches in Git 관련
A branch is just a named reference to a commit.
We could always reference a commit by its SHA-1 hash, but humans usually prefer other forms to name objects. A branch is one way to reference a commit, but it’s really just that.
In most repositories, the main line of development is done in a branch called master
. This is just a name, and it’s created when we use git init
, making it is widely used. However, it’s by no means special, and we could use any other name we’d like.
Typically, the branch points to the latest commit in the line of development we are currently working on.
To create another branch, we usually use the git branch
command. By doing that, we actually create another pointer. So if we create a branch called test
, by using git branch test
, we are actually creating another pointer that points to the same commit as the branch we are currently on.
How does git
know what branch we’re currently on? It keeps a special pointer called HEAD
. Usually, HEAD
points to a branch, which in turns points to a commit. In some cases, HEAD
can also point to a commit directly, but we won’t focus on that.
To switch the active branch to be test
, we can use the command git checkout test
. Now we can already guess what this command actually does — it just changes HEAD
to point to test
.
We could also use git checkout -b test
before creating the test
branch, which is the equivalent of running git branch test
to create the branch, and then git checkout test
to move HEAD
to point to the new branch.
What happens if we make some changes and create a new commit using git commit
? Which branch will the new commit be added to?
The answer is the test
branch, as this is the active branch (since HEAD
points to it). Afterwards, the test
pointer will move to the newly added commit. Note that HEAD
still points to test
.
So if we go back to master by git checkout master
, we move HEAD
to point to master
again.
Now, if we create another commit, it will be added to the master
branch (and its parent would be commit B2424).