Skip to content

Instantly share code, notes, and snippets.

@Justintime50
Last active October 3, 2022 16:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Justintime50/fe05a64c0b75fe6c9bb76bdc2d147898 to your computer and use it in GitHub Desktop.
Save Justintime50/fe05a64c0b75fe6c9bb76bdc2d147898 to your computer and use it in GitHub Desktop.
Learn about various operations of a Git branch

Working with Git Branches

This document contains various operations you can use when working with Git branches such as moving commits, updating branch names, creating branches from a tag, etc.

Move a Commit to Another Branch

New Branch

git branch newbranch
git reset --hard HEAD~1
git checkout newbranch

Existing Branch

git checkout existingbranch
git merge master
git checkout master
git reset --hard HEAD~1
git checkout existingbranch

Attribution

Update Branch Name

Run the following commands to update your local repository's branch and push that change to the origin

git branch -m <OLD_BRANCH> <NEW_BRANCH>
git fetch origin
git branch -u origin/<REMOTE_BRANCH> <LOCAL_BRANCH>

Create a Branch from a Tag

git checkout -b <NEW_BRANCH_NAME> <EXISTING_TAG_NAME>

Reset Branch to Origin

git reset --hard @{u}

Replace Branch with Another Branch and Keep Commits (Non-Nucler)

This will replace the changes from one branch with another, avoid merge conflicts, and keep commit history intact.

# Assumes you want to put changes from `feature_branch` to `master`
git checkout feature_branch
git merge -s ours master
git checkout master
git rebase feature_branch

Replace a Branch with Another Branch (Nuclear)

This will delete all files and replace with the new ones, good to avoid large merge conflicts when a feature branch diverged and must now become "master".

# Be on the branch you want to replace (eg: master)
rm -r ./*
git checkout feature_branch -- .
git add .
git commit -m "chore: replace branch"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment