Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Git: move last commit from branch to master

Tags:

git

svn

bitbucket

I have 2 commits: A and B. Both are independent from each other and contain different files. I have 2 branches: master and branch1:

master: A
branch 1: A, B

I need to remove branch 1 and to move commit B to master. I tried to do that with

git cherry-pick B,

but it just copied B into A, while I need it to have the same commit number and - most importantly - to save the comments that are there!

Is there any way? I've looked through different answers and really unsure of what to do with my situation.

like image 914
woodStone Avatar asked Dec 20 '16 21:12

woodStone


1 Answers

You have two options, a merge, or a rebase.

Merge

Merging branch1 into master is the simplest operation to understand, and the option I would recommend. However, it will appear as a new commit on the master, with a different commit id.

We will take the new commits from branch1 and attempt to merge them into master as a new changeset which we can then commit. This will preserve the history of both branch1 and master.

From the command line, you would execute the following steps:

1) First checkout the branch you wish to merge into

git checkout master

2) Now merge in your branch, using the --no-ff option

git merge --no-ff branch1

3) You can now delete the old branch if desired

git branch -d branch1

Rebase

The alternative approach is to perform a rebase.

By rebasing your branch 1 onto master, you will effectively replay the commit history of branch1 onto the master. Afterwards, it will appear as though you had originally checked commit 'b' into master, preserving your commit id.

Again, from the command line, you would execute the following steps:

1) First checkout the branch you want to rebase into

git checkout master

2) Now rebase your branch into the master

git rebase branch1

Note - there are some caveats with rebasing, and if you don't fully understand how it works, it's safer to use a merge instead.

If in doubt - merge, don't rebase.

like image 163
Hywel Rees Avatar answered Oct 04 '22 17:10

Hywel Rees