Git Branches¶
Working with Branches¶
Working with Git branches always used to be done with checkout
.
The modern way to work with branches is with branch
/switch
.
Creating Git Branches¶
Create a branch using:
branch-name
.The second will both create and switch to the new branch.
Switch Branch¶
Use git switch
to switch to a given branch.
List Branches¶
Get a list of all the current branches with branch -l
.
Update Branch References¶
Prune deleted remote branches¶
When a branch is deleted remotely, you'll need to update your local references.
Or, to be more explicit:
This assumes the branch was deleted in theorigin
remote.
Prune deleted local branches¶
If you've ever switched to the branch before, it might still exist in the Git reflog.
-
git reflog --expire=now --all
: Prunes entries older than the specified time.--expire=now
prunes all reflog entries older than today.git gc --prune=now
: This cleans up unnecessary files.--prune
prunes "loose" objects (objects older than thetime
given).- This is on by default, but the
time
is set to 2 weeks.
Check if the branch still exists.
If the branch still isn't gone, delete it manually from .git/refs/heads/
Pruning Remote Branches¶
Once you've deleted branches locally, they may still exist on your remote.
Prune a Single Remote Branch¶
If you need to delete a single remote branch that you've deleted locally, you can
use git push
with the --delete
option:
# Delete a single remote branch on Github explicitly
git push origin --delete branch-name
# or, use the refspec delete syntax
git push origin :branch-name
branch-name
on GitHub.
- The
:branch-name
syntax is the refspec delete form.- It means "push 'nothing' to
branch-name
," which instructs the remote to delete that ref.
- It means "push 'nothing' to
Bulk Prune Branches¶
If you want to prune all remote branches that were deleted locally, you can do a dry run first:
-
'refs/heads/*:refs/heads*
: Specifies source side and destination side.refs/heads/*
: Source side. All local branches.refs/heads/*
: Destination side. All remove branches underrefs/heads
(normal branches).
-
Using
--prune
with refspecs deletes remote branches under the destination side of your refspec that have no matching source on your local side. -
This does not touch tags unless they're included in the refspec.
If that looks good, you can do a real run:
This:
- Pushes all local branches to
origin
- Deletes any remote branch under
refs/heads/*
that has no corresponding local branch - Safer than
--mirror
because it only targets branches (not tags, notes, etc.)
Bulk Prune All Refs (Mirror)¶
You can also mirror everything.
This method mirrors all refs (branches, tags, notes), additions, updates, and deletions.
This is a destructive operation.
Do a dry run first:
Only use this method if you truly want the remote to be an exact mirror of the local repository.