Git Branch-Related Commands Guide

Branch-Related Commands

git branch - Branch Management

Creates, lists, and deletes branches.

Option Description
-a, --all Display all branches (including remote branches)
-d, --delete Delete a branch
-D Force delete a branch
-m, --move Rename a branch
-v, --verbose Display the latest commit for each branch

Examples:

git branch - List local branches
git branch feature - Create a new branch
git branch -a - List all branches (including remote branches)
git branch -d feature - Delete a merged branch
git branch -D feature - Force delete a branch regardless of merge status
git branch -m old-name new-name - Rename a branch

git checkout - Switch Branches and Restore Files

Switches branches or restores files in the working directory.

Option Description
-b <branch-name> Create a new branch and switch to it
-B <branch-name> Create a new branch if it doesn't exist, or reset it if it exists, then switch to it
-f, --force Force switch even if there are uncommitted changes (changes will be lost)
-- Separator to distinguish between file paths and branch names

Examples:

git checkout develop - Switch to the develop branch
git checkout -b feature - Create a new feature branch and switch to it
git checkout -- file.txt - Discard changes to file.txt (restore to the state of the last commit)
git checkout HEAD~1 file.txt - Restore file.txt to the state from one commit before
git checkout origin/main - Switch to the state of the remote main branch

git switch - Switch Branches (Git 2.23 and later)

A dedicated command for switching branches (splits functionality from checkout).

Option Description
-c <branch-name> Create a new branch and switch to it
-C <branch-name> Create a new branch if it doesn't exist, or reset it if it exists, then switch to it
-d, --detach Switch to a specific commit (detached HEAD state)
--discard-changes Discard uncommitted changes when switching

Examples:

git switch main - Switch to the main branch
git switch -c feature - Create a new feature branch and switch to it
git switch -C feature - Create a new feature branch if it doesn't exist, or reset it if it exists, then switch to it
git switch -d HEAD~3 - Switch to the commit three commits before HEAD (detached HEAD state)
git switch - - Return to the previous branch