Branches#
A branch is a reference to a commit, and can be moved to some future commit. This page gives an overview of the tools git has to work with branches.
Overview#
This section provides an overview of the basics of dealing with branches in git
:
git branch
for listing available branches.git branch <branch_name>
for creating a new branch.git checkout <branch_name>
for switching between branches.How a branch reacts to the creation of a new commit while
HEAD
refers to that branch.
We will consider the typical operations with git branches with the repository created in the following cell as example.
mkdir /tmp/branches_overview
cd /tmp/branches_overview
git init &> /dev/null
A newly created repository will only contain the master
branch. The next cell shows the log
of the repo after the first commit.
echo "some text" &> some_files
git add --all
git commit -m "first commit" &> /dev/null
git log --decorate
commit 96a988189f4be3526ff4e2bb4e48a192cd4f08c9 (HEAD -> master)
Author: fedor <kobfedsur@gmail.com>
Date: Wed Jan 8 17:25:50 2025 +0300
first commit
The following cell shows awailable branches by using git branch
.
git branch
* master
There is only the main
branch. The following code creates an extra branch, new_branch
, and lists available branches.
git branch new_branch
git branch
* master
new_branch
Now, in git log
, you can see that both master
and new_branch
refer to the same commit. However, the syntax HEAD -> master
indicates that the master
branch is currently being used.
git log
commit 96a988189f4be3526ff4e2bb4e48a192cd4f08c9 (HEAD -> master, new_branch)
Author: fedor <kobfedsur@gmail.com>
Date: Wed Jan 8 17:25:50 2025 +0300
first commit
With git checkout new_branch
you can set new_branch
as the branch that HEAD
points to.
git checkout new_branch
git log
Switched to branch 'new_branch'
commit 96a988189f4be3526ff4e2bb4e48a192cd4f08c9 (HEAD -> new_branch, master)
Author: fedor <kobfedsur@gmail.com>
Date: Wed Jan 8 17:25:50 2025 +0300
first commit
But what does HEAD -> new_branch
actually mean? During a git commit
, HEAD
points to the new commit, and the branch it refers to moves along with it. The following cell creates a new commit and displays the resulting git log
.
echo "hello" > new_file
git add --all
git commit -m "add new file" &> /dev/null
git log --all --graph
* commit 4a10dac0f6c48e7556e066a1348de4ef7b30719c (HEAD -> new_branch)
| Author: fedor <kobfedsur@gmail.com>
| Date: Wed Jan 8 17:25:58 2025 +0300
|
| add new file
|
* commit 96a988189f4be3526ff4e2bb4e48a192cd4f08c9 (master)
Author: fedor <kobfedsur@gmail.com>
Date: Wed Jan 8 17:25:50 2025 +0300
first commit
As a result, HEAD
and new_branch
, which HEAD
referred to, have moved to the new commit.