Introduction to branches
A branch is like a parallel universe of the git repo, by default the default branch of a git repo is main, if we create a new branch by doing :
git branch example-branch
the new example-branch
could have it’s own files and its own versions of files that are present in main, it’s really like a parallel universe!
Branches are useful when we want to add a new feature or to fix a bug, that way we create a branch called bug-fix (in the example of fixing a bug), and work on the project simultaneously without affecting the main project (we are branching-off), even if we have problems in our current project that won’t affect the live project because it’s getting served by the main branch.
We could switch between branches using :
git switch example-branch
We could also create and switch to a new branch at the same time :
git switch -c example-branch
To check our branches :
git branch
When we are okay with the result in the branch, now it’s time to merge back into the main branch, this is presented in this simple illustration :
Modifying and comparing branches
To compare two branches, like we compare two commits, or to compare file (staged or unstaged) to the latest commit etc … :
git diff main example-branch
If we get into the trouble of confusing branch names, we need to resolve the issue by renaming the branches by a more clear name :
git branch -m old-branch-name new-branch-name
It’s good practice to delete the branch after finishing with it and merging with the main branch to do this we execute the following command :
git branch -d example-branch
If example-branch
hasn’t been merged to main
and we did the last command we will get an error, if we want to force the deletion :
git branch -D example-branch
Merging branches
When merging branches the branch that we want to merge from (the one with the new feature) is called the source
branch, and the branch that we want to merge into is called the destination
branch, the last commits from each branch are called the parent commits
, if we want to merge example-branch
into main
we need first to switch to the main branch :
git switch main
and then merge :
git merge example-branch
If we want to merge the two branches without switching to main we can do so using this command :
git merge source destination
git merge example-branch main
Note : the source being the first branch (order is important)