← Back to Git Course | Chapter 3: Branching | Lesson 2 of 9

Git branch Command

Listing Branches

git branch on its own lists every local branch in your repository, marking your current one with an asterisk; add -r to see remote-tracking branches instead, or -a to see both local and remote together.

Example: Listing Branches

bash
git branch
git branch -r
git branch -a

Creating a New Branch

git branch <name> creates a new branch pointing at your current commit without switching to it; adding a starting commit hash instead lets you branch off from any specific point in history, not just where you currently are.

Example: Creating a New Branch

bash
git branch feature-cart

Deleting a Branch

git branch -d <name> deletes a branch, but only if its commits have already been merged elsewhere -- Git blocks the deletion otherwise to protect unmerged work, and you'd need the more forceful -D to override that safeguard.

Example: Deleting a Branch

bash
git branch -d feature-cart
git branch -D feature-cart

Renaming a Branch

git branch -m <old> <new> renames a branch -- run without arguments except the new name to rename whichever branch you currently have checked out, or specify both names to rename a branch you're not currently on.

Example: Renaming a Branch

bash
git branch -m old-name new-name

Inspecting Upstream Branches

git branch -vv shows each local branch alongside its remote-tracking counterpart and how many commits ahead or behind it is, which is the fastest way to spot branches that need a push or a pull before continuing work.

Example: Inspecting Upstream Branches

bash
git branch -vv

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.