Skip to main content
Knowledge Hub

Branches in Git

Understanding Git branches and how to work with them

Branches in Git

Branches are a core feature of Git that allow you to work on different versions of your code simultaneously.

What are Branches?

A branch in Git is essentially a lightweight movable pointer to a commit. The default branch is usually called main or master.

Why Use Branches?

Branches allow you to:

  • Work on features without affecting the main codebase
  • Experiment with new ideas safely
  • Collaborate with team members
  • Maintain multiple versions of your project

Creating Branches

Create a New Branch

git branch feature-branch

Switch to a Branch

git checkout feature-branch

Or use the newer command:

git switch feature-branch

Create and Switch in One Command

git checkout -b feature-branch

Or:

git switch -c feature-branch

Working with Branches

List All Branches

git branch

The current branch will be marked with an asterisk (*).

List Remote Branches

git branch -r

List All Branches (Local and Remote)

git branch -a

Merging Branches

Merge a Branch into Current Branch

git merge feature-branch

Merge Strategies

Git offers several merge strategies:

  • Fast-forward merge: When there are no conflicts
  • Three-way merge: When branches have diverged
  • Squash merge: Combines all commits into one

Deleting Branches

Delete a Local Branch

git branch -d feature-branch

Force delete (if branch hasn’t been merged):

git branch -D feature-branch

Delete a Remote Branch

git push origin --delete feature-branch

Best Practices

  1. Use descriptive branch names: feature/user-authentication is better than branch1
  2. Keep branches short-lived: Merge or delete branches regularly
  3. Use a branching strategy: Git Flow, GitHub Flow, or GitLab Flow
  4. Protect main branch: Use branch protection rules on GitHub

Common Branching Workflows

Feature Branch Workflow

  1. Create a feature branch from main
  2. Make changes and commit
  3. Push branch to remote
  4. Create a pull request
  5. Review and merge

Git Flow

A more structured approach with:

  • main: Production-ready code
  • develop: Integration branch
  • feature/*: New features
  • release/*: Preparing releases
  • hotfix/*: Emergency fixes