简体   繁体   中英

Git: Can I move\merge changes from branch to branch?

I have the following problem. I assume some of you also have it from time to time:

Sometimes, I forget to create a feature branch and start to make the changes on the master branch.

I still did not commit those changes.

What I do usually is to keep the changes on the side, revert, create the new FB and merge the changes.

Is there a more elegant way to solve this situation?

If it relevant too, I am working with InteliJ, but cmd line solutions are also welcomed.

The better approach would be execute the following commands.

Switch to your feature-branch or creates and switch to it if the branch doesn't exist.

git checkout -b feature-branch

If you want to save your changes on your feature-branch so it belongs to it:

git add . # Stage the file for commit to your local repository.
git commit -m "Add comment" # Commit the file that you've staged in your local repository.
git push origin feature-branch # Push the changes in your local repository to GitHub.

To clean your branch if you don't want to keep the changes you did not commit, you can use the following command.

git reset --hard HEAD

It will erase all changes in your working tree, so that your current files match the content of the HEAD.

When this happens, if it is not a problem to point a revision to an earlier revision (which can a problem if you have already pushed the dev branch), you can do this:

git checkout -b my-feature-branch # create feature branch right where I am right now
git branch -f dev HEAD~10 # set dev 10 revisions behind.... you could also use a revision ID instead of HEAD~x

And that's it.

If you have not yet made any commits, then all you have to do is create a new branch at your current location:

git checkout -b feature-branch

The git checkout -b command creates a new branch at your current location (which would be the tip of the master branch for you) and checks out that branch (meaning new commits will be on that branch.) Your work tree remains unchanged. Note that uncommitted changes do not yet belong to any branch. You can continue to work on your feature and commit when ready.

No need to copy your changes anywhere else, nor clear your worktree with git stash or git reset --hard and copy/merge your changes back in.

For storing changes: git stash. For unstash: git stash pop

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