Skip to main content

Git Branches

Git branches are used to develop features, fix bugs, and experiment with new ideas. They allow you to split up development work and manage different lines of development in parallel.

Creating Branches

Creating a new branch is simple and allows you to work on features in isolation.

Create a New Branch

Use git checkout -b <branch> to create a new branch with the specified name and switch to it:
Alternatively, you can use git branch <branch> and then git checkout <branch> separately.

Create an Empty Branch

If you want to create an empty branch without any history, use git checkout --orphan <branch>:
This is useful for setting up branches with entirely different content or history from your main branch.

Switching Branches

You can easily switch between branches using git checkout or the newer git switch command.

Switch to an Existing Branch

Switch to the Previous Branch

Use - as a shorthand for the previous branch:

Viewing Branches

List all branches in your repository:

Merging Branches

At some point, you’ll want to merge a branch into another branch, usually master or main.

Basic Merge

Switch to the target branch first, then merge the source branch:
By default, Git will use fast-forward merge to create a linear history.

Creating a Merge Commit

If you want to create a merge commit, use the --no-ff flag:

Deleting Branches

As your project progresses, you may accumulate branches that are no longer needed. Deleting these branches keeps your repository clean and organized.

Delete Local Branch

Use git branch -d <branch> to delete a local branch:
Note that you need to switch to a different branch before deleting the target branch.

Delete Remote Branch

Use git push -d <remote> <branch> to delete a remote branch:

Delete Detached Branches

Detached branches are branches that are not associated with any commit. Use git fetch --all --prune to garbage collect them:
This is especially useful if the remote repository is set to automatically delete merged branches.

Delete Merged Branches

You can delete all branches that have been merged into a target branch:

Branch Workflows

Feature Branch Workflow

Bugfix Workflow

Best Practices

  • Use descriptive branch names (e.g., feature/user-auth, bugfix/login-error)
  • Keep branches focused on a single feature or fix
  • Regularly merge or rebase with the main branch to avoid conflicts
  • Delete branches after they’ve been merged
  • Use merge commits (--no-ff) for feature branches to preserve history
  • Create branches from an up-to-date main branch