# Branch
A branch
is a line of commits inside a repo.
Every git repository has a main branch, usually called master
or main
, that branch includes all the commits that are a part of the final code of the project.
Is is usefull to create a new branch from another branch, to be able to make changes in the code withour affecting the code of the main branch, and once finalized the work you are doing in that branch, that branch (and the commits in it)can be included or merged
in the main branch.
In order to create a new branch from another branch, you need to run the following:
git checkout base-branch
git branch my-new-branch
git checkout my-new-branch
git checkout base-branch
moves you to the branch you want to part from.
git branch my-new-branch
creates a new branch based on the branch you are, and will be exactly the same as that base branch, that means it will contain all of the commits of the base branch.
git checkout my-new-branch
will take you to the branch you just created.
A usefull shortcut to create a new branch and move to it:
git checkout -b my-new-branch
Once you are done with the work in that new branch, you need to commit
the changed you've made, and if everything is working fine, you include or merge
that branch into the main branch.
In order to merge two branches, you move to the base branch, and run the merge
command:
git checkout base-branch
git merge my-new-branch
This action will include all the commits you made in my-new-branch
into the base-branch
branch.
Once you branch is merged, you can delete it without any risk of losing the changes you made, since they are part of base-branch
now.
To delete a branch, you use the following command:
git branch -d my-new-branch