How replace a branch in Git with another branch without merge

Viewed 1566

My repo structure is like this.

  • branch 'dev' - Created from 'master' and is current.
  • branch 'master' - No commits for last 2 years. But few commits (unwanted) ahead of 'dev'.

Now my need is to make the 'master' code exactly same to 'dev'. I guess, a merge would cause the unwanted commits on 'master' to be retained. Any help?

2 Answers

You may do a hard reset on master to the current dev branch:

# from master
git checkout master
git reset --hard dev

But keep in mind that this may potentially discard any commits on master which were unique to that branch. If this be a concern of yours, then consider branching off from master as a safety precaution.

The next time you push master to the remote you will probably have to force push:

git push --force origin master

The reason for force pushing is that you have rewritten the base of the master branch and Git won't accept a regular push.

Tim's answer works great, let's just add this variant for the record :

# from any branch
git branch -f master dev

And the warning about losing the contents of the old dropped branch is the same, a backup is cheap, so maybe consider this :

git branch backup_old_master master
git branch -f master dev

Then master will point to the exact same commit (and history) dev currently points to, and you'll have backup_old_master just in case.

Related