Branch is a lightweight, movable pointer to a commit. The default branch name in Git is typically "master," but you can create and switch to other branches to isolate work and manage changes more efficiently. Branches are an essential part of Git's flexibility and support for parallel development. They allow multiple developers to work on different features or bug fixes simultaneously without interfering with each other. Branches also enable you to experiment with new ideas without affecting the main codebase until you are ready to merge changes.
Key concepts related to branches in Git:
Default Branch:
- When you initialize a new Git repository or clone an existing one, Git creates a default branch called "master." However, note that some repositories now use "main" as the default branch name.
Creating a Branch:
You can create a new branch using the
git branch
command. For example:git branch new-feature
Switching Between Branches:
The
git checkout
orgit switch
commands allow you to switch between branches. For example:git checkout new-feature
or
git switch new-feature
Creating and Switching in One Step:
You can create a new branch and switch to it in a single command using the
-b
option withgit checkout
orgit switch
:git checkout -b new-feature
or
git switch -c new-feature
Viewing Branches:
To see a list of branches in your repository and identify the currently active branch, use:
git branch
Merging Branches:
After making changes in a branch, you can merge those changes back into another branch using the
git merge
command. For example:git checkout main git merge new-feature
Deleting a Branch:
Once a branch is no longer needed, you can delete it using the
git branch -d
command. For example:git branch -d new-feature
Deleting Remote Branch:
To delete a branch on remote use
git push <remote name> :<branch name>
command. For example:git push origin :new-feature
Renaming a Branch:
You can rename a branch using the
git branch -m
command. For example, to rename "feature-abc" to "new-feature":git branch -m feature-abc new-feature