Branching in Git
Branching in Git is a powerful feature that allows you to work on different versions of your
project simultaneously. Here's a quick overview to help you get started:
Basic Concepts
● Branch: A branch in Git is a lightweight movable pointer to one of these commits. The
default branch name in Git is main (formerly master).
● Commit: A snapshot of your project at a specific point in time. Each commit has a
unique ID.
● HEAD: A pointer to the current branch reference, and thus to the latest commit on that
branch.
Common Commands
1. Create a New Branch
git branch <branch-name>
This creates a new branch but doesn't switch to it. To create and switch to a new branch
in one command, use:
git checkout -b <branch-name>
2. Switch Branches
git checkout <branch-name>
You can also use git switch:
git switch <branch-name>
3. List Branches
git branch
This will show all local branches. To see remote branches, use:
git branch -r
4. Merge Branches
First, switch to the branch you want to merge changes into (usually main):
git checkout main
Then merge another branch into it:
git merge <branch-name>
If there are conflicts, Git will prompt you to resolve them. After resolving, you need to
stage the resolved files and commit the merge.
5. Delete a Branch
o Locally:
git branch -d <branch-name>
Use -D to force delete if the branch has unmerged changes.
o Remotely:
git push origin --delete <branch-name>
6. Rebase
Rebase is another way to integrate changes from one branch into another, but it rewrites
commit history.
Copy code
git checkout <branch-name>
git rebase main
This re-applies commits from <branch-name> on top of the main branch.
Tips
● Keep Branches Small: Small, focused branches are easier to manage and review.
● Regularly Merge or Rebase: To keep branches up-to-date with the main codebase and
avoid large merge conflicts.
● Use Descriptive Names: Naming branches clearly helps everyone understand the
purpose of the branch.
Branching strategies vary based on the project's complexity and team practices. Popular
strategies include Git Flow, GitHub Flow, and GitLab Flow. Each has its own benefits and use
cases, so you might want to explore those to find what fits best for your workflow.