简体   繁体   中英

Git ahead of master, how to put the changes into a new local branch?

I'm in the

Your branch is ahead of 'origin/master' by 2 commits.
(use "git push" to publish your local commits)

state after making and committing some changes in my local master branch.

How do I pick off the local changes into a new branch?

My desired outcome is: local/master is synchronized with origin/master, and I have a local branch with the two commits in it.

First

git checkout -b newBranchName

this will create a new branch, the same as the current master you are working on.

After that,

git checkout master

this will select master as your current branch.

Finally

git reset --hard origin/master

this will remove those 2 commits from master, but they will be still available in newBranchName

EDIT: as @ShmulikKlein Mention, be careful with --hard .. you can always use --soft and then discard the changes

@Matias is right, but first, you should be very careful when using git reset --hard as along with revretting the last 2 commits, it will also wipe out your entirely working directory and staging area (aka, unstaged and uncommited changes).

Second, I think that the last step should be git reset --hard HEAD~2 when you are on the master branch, since you are only want to revert the last 2 commits, since you don't know how origin/master was changed since you post the question... (unless you check using git status ...)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM