Branches are a core feature of Git which allows us to work with different versions in parallel histories.
Note: throughout this tutorial, I’ll be using <
and >
symbols to show the commands, however, these symbols are not required to implement them. I just wanted to comment on it 😎. Now, let’s go with the article.
Creating Branches
The names can’t have spaces. If you need to make a separation use symbols like: -
or _
.
git branch <new-branch>
git checkout vs git switch
You can have as many branches as you want in the repository; to switch between a branch and another there are two commands: git checkout
and git switch
.
Git checkout is used on many other aspects of Git besides branches; while git switch
is used only for branches which decreases the margin for error and it’s the best way to switch branches.
I recommend git switch
.
Renaming
To change the name of the branch you’re in:
git branch -m <head-branch-new-name>
To rename a specific branch:
git branch -m <old-name-branch> <new-name-branch>
Delete Branches
To delete branches locally:
git branch -d <branch>
git push origin --delete <branch>
And to delete a branch from the remote repository use this command:
git push origin :<branch>
Just make sure that nobody in your team depends on the changes in that branch.
Merge
git merge
works to integrate the changes between branches. This integration is commonly referred to as “merge”; it keeps the branch history of “commits” intact and creates a new “commit” for the branch receiving the changes.
First, switch to the branch in which you want to receive the changes, then use the following command:
git merge <incoming-branch>
Rebase
It's another way of integrating the changes of a commit history between two branches. It changes the commit history by making the integration a straight line and not a combination of branches.
Like in git merge
, you have to switch to the branch in which you want to receive the changes, then use the command:
git rebase <incoming-branch>
Comparing Branches
Check which commits are in branch-b, but not on branch-a.
To check which commits are in one branch (branch-b) and not in another (branch-a) use this command:
git log <branch-a>..<branch-b>
You can also use it to compare them with the remote branches.
It was a short post but I just wanted to challenge myself to write so I told myself that I was gonna do this no matter what, so here it is. I hope I was useful to you.
That’s it for me, but you can follow me on LinkedIn, Twitter, Instagram, Facebook, Github, Reddit and here in Hashnode. Also, you can subscribe to my newsletter down below 👇. Well, see ya!