X
Popular Searches

How to Move Changes to Another Branch in Git

While Git keeps track of your day to day 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 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.

Advertisement

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
Advertisement

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.

Anthony Heddings Anthony Heddings
Anthony Heddings is the resident cloud engineer for LifeSavvy Media, a technical writer, programmer, and an expert at Amazon's AWS platform. He's written hundreds of articles for How-To Geek and CloudSavvy IT that have been read millions of times. Read Full Bio »

The above article may contain affiliate links, which help support CloudSavvy IT.