Developer Tools

How do I use a Git branch?

Updated 2026-08-14

✓

Quick answer

To use a Git branch, you can create a new branch, switch to it, and then commit changes independently from the main branch.

This guide explains how to create, switch, and manage branches in Git, allowing for parallel development.

Steps

  1. 1

    Create a new branch

    Run `git branch feature-xyz` to create a new branch named 'feature-xyz'.

  2. 2

    Switch to the new branch

    Execute `git checkout feature-xyz` or `git switch feature-xyz` to start working on the new branch.

  3. 3

    Make changes and commit

    After making changes, stage them with `git add .` and commit using `git commit -m 'Your message'`.

  4. 4

    Merge changes back to main branch

    Switch back to the main branch with `git checkout main` and merge your changes using `git merge feature-xyz`.

Creating a Branch

Use the command `git branch <branch-name>` to create a new branch. This does not switch to the new branch immediately.

Switching Branches

To switch to a branch, use `git checkout <branch-name>`. In newer versions of Git, you can also use `git switch <branch-name>`.

Merging Branches

To merge changes from one branch into another, switch to the target branch and use `git merge <branch-name>`.

Watch out for

  • Merging branches can lead to conflicts if changes overlap; resolve conflicts before completing the merge.
  • Ensure you commit or stash changes before switching branches to avoid losing work.

FAQ

What is the difference between `git checkout` and `git switch`?

`git checkout` can be used for both switching branches and restoring files, while `git switch` is specifically for switching branches.

Can I delete a branch after merging?

Yes, you can delete a branch using `git branch -d <branch-name>` after merging it, but ensure that you no longer need it.

How do I see all branches in my repository?

Use the command `git branch` to list all local branches, and `git branch -a` to see both local and remote branches.