Skip to main content

Branching

Previously we learned about how Git stores the cthe contents of a commit and references to files at a point in time.

Git walks the tree objects to get the contents of a commit and builds out the filesystem.

Branches are essetially pointers to commits.

When you make a commit, the branch pointer moves to the new commit.

This is highly efficient because Git only needs to store the new commit and the branch pointer.

This is why Git is so fast and efficient.

src

Check the Current Branch

To check what branch you are currently on, use the git branch command.

git branch
* master
tip

Must be in an initialized git project

Rename the Branch

To rename a branch use the following command

git branch -m <old-branch-name> <new-branch-name>

Create a New Branch

Be mindful when creating a new branch it creates a new branch from your current location (HEAD location). This means if you are not on the master branch, it will not create the new branch from master but from the branch you are currently on.

tip

If you run a git log on the current branch and a git log on the new branch. They will have the same hashes and content.

To create a new branch there are a few options.

  1. Create a Branch
git branch new-branch-name

This creates a new branch but does not switch context to the new branch.

  1. My favorite is to use the git checkout -b way.
git checkout -b new-branch-name

This will create a new branch and switch to it.

  1. You can also use the git switch command
git switch -c new-branch-name

This will create a new branch and switch to it if it doesnt exist (-c).

Switch Branches

To switch branches use the git checkout or git switch command.

git checkout branch-name

or

git switch branch-name