How to Move Changes to Another Branch in Git



Key Takeaways

  • Git helps organize changes with branches, but wrong commits can cause problems.
  • To move changes, switch branches using the “git checkout ” command.
  • To correct committed mistakes, soft reset before switching so your changes aren’t commited yet.

While Git keeps track of your daily changes, it also features systems like branches that help you organize. If you’re not careful, though, you can end up with problems like commits and changes made to the wrong branch that can be difficult to solve without the right commands.

Moving Changes (If You Haven’t Committed Yet)

Git watches over your whole folder, but changes you make to files are not tied to a specific Git branch until you commit them. You can move branches, and bring those changes along with you.

The simplest option is to simply switch branches, but this will only work if the two branches you’re targeting have a matching history:

git checkout feature

You can get around this in a few ways. The first is by making a new branch, and then merging the diverging histories:

        git checkout -b tempfeature

git checkout feature

git merge tempfeature

You can also use git stash to store changes for later, and reapply them on a new branch:

        git stash

git switch feature

git stash apply

Moving Commits (If You Already Committed)

If you already committed, don’t worry; you can always soft reset, so commits are not final until pushed to remote source control. If you did that already, you can still fix the problem, but the record of your mistake will live on in your Git history, so it’s best to do it locally before your coworkers see it.

To undo commits, you can simply soft reset, usually just undoing the last commit made, but you can also pass in a reference to the commit ID:

git reset HEAD~1

This will leave you at the “haven’t committed yet” state, after which you can use the methods above to fix the problem.

Alternatively, you can use git cherry-pick. This command copies commits from one branch to another, and is a nice way of picking out commits and moving them to new branches in a clean manner.

Run git log to find the ID of the commit you want to revert:

git log

Then checkout the feature branch, assuming your changes have been committed, and run cherry-pick:

        git switch feature

git cherry-pick

After that, there will still be a duplicate commit on the main branch. You can reset this and discard the changes if the feature branch is in proper order, or keep it and let Git sort it out once you merge.


If you want to learn more about using Git, read about how you can always know what branch you’re in, or see if you know all the basic Git commands.



Source link

Previous articleChatGPT Is Helping Siri in iOS 18.2. And It’s Actually Useful.
Next articleShould you ditch unencrypted messaging apps? Here’s what the experts say about the FBI’s warning