Git Branch
A branch is a separate line of work. With a branch you can build a new feature or fix a bug without disturbing the main code. When your work is ready, you merge the branch back. This is the most powerful feature of Git.
Technically, a branch is only a small pointer to a commit, so creating a branch in Git is very fast and uses almost no space.
Why use branches?
- Work on many features at the same time, without them mixing.
- Keep the
mainbranch always working and clean. - Try an idea safely. If it fails, delete the branch.
- Help code review, because a branch can be reviewed before the merge.
Syntax
git branch
git branch <name>
git branch -m <old> <new>
git branch -d <name>
git branch -D <name>
List the branches
$ git branch
* main
The star (*) is the current branch. A new repository has only one branch, which is main here (it can be master in older setups).
Create a new branch
$ git branch feature-cart
$ git branch
feature-cart
* main
The star is still on main. Creating a branch does not move you to it. To move, use git switch. A short way to create and move together is git switch -c feature-cart.
See the last commit of each branch
$ git branch -v
feature-cart 52a1595 Add home page
* main 52a1595 Add home page
Rename a branch
$ git branch -m feature-cart feature-basket
$ git branch
feature-basket
* main
To rename the branch you are on now, you can give only the new name: git branch -m new-name.
Delete a branch
First we add a commit on the new branch, to see the safety check of Git.
$ git switch feature-basket
Switched to branch 'feature-basket'
$ echo "basket" > basket.html
$ git add .
$ git commit -q -m "Add basket page"
$ git switch main
Switched to branch 'main'
$ git branch -d feature-basket
error: the branch 'feature-basket' is not fully merged
hint: If you are sure you want to delete it, run 'git branch -D feature-basket'
hint: Disable this message with "git config set advice.forceDeleteBranch false"
Git refuses, because the commit of feature-basket is not merged in any other branch, and you could lose it. The lowercase -d is the safe delete. The capital -D forces it.
$ git branch -D feature-basket
Deleted branch feature-basket (was 8583328).
$ git branch
* main
Delete a remote branch
git push origin --delete feature-basket
Other useful options
| Command | Meaning |
|---|---|
git branch -a | List local and remote branches |
git branch -r | List only the remote branches |
git branch --merged | Branches already merged in the current branch |
git branch --no-merged | Branches not merged yet |
git branch --show-current | Print only the name of the current branch |
Branch naming tips
- Use lowercase and dashes:
feature-login,fix-header-bug. - Add a short prefix for the type:
feature/,bugfix/,hotfix/. - Do not use spaces. Keep names short but clear.
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |