Git Branch Cheat Sheet

From WikiOD

Here is the cheatsheat of Git Branch and basic guide on how to use Git Branch

Working with branches[edit | edit source]

{: .-three-column}

Creating[edit | edit source]

git checkout -b $branchname
git push origin $branchname --set-upstream

Creates a new branch locally then pushes it.

Getting from remote[edit | edit source]

git fetch origin
git checkout --track origin/$branchname

Gets a branch in a remote.

Delete local remote-tracking branches[edit | edit source]

git remote prune origin

Deletes origin/* branches in your local copy. Doesn’t affect the remote.

List existing branches[edit | edit source]

git branch --list

Existing branches are listed. Current branch will be highlighted with an asterisk.

List merged branches[edit | edit source]

git branch -a --merged

List outdated branches that have been merged into the current one.

Delete a local branch[edit | edit source]

git branch -d $branchname

Deletes the branch only if the changes have been pushed and merged with remote.

Delete branch forcefully[edit | edit source]

git branch -D $branchname
git branch -d $branchname

Note: You can also use the -D flag which is synonymous with –delete –force instead of -d. This will delete the branch regardless of its merge status. Delete a branch irrespective of its merged status.

Delete remote branch[edit | edit source]

git push origin --delete :$branchname

Works for tags, too!

Get current sha1[edit | edit source]

git show-ref HEAD -s

Reset branch and remove all changes[edit | edit source]

git reset --hard

Undo commits to a specific commit[edit | edit source]

git reset --hard $commit_id

# Now push safely to your branch
git push --force-with-lease

# Or push brutally to your branch
git push --force