As said by other you can use stash
or checkout --merge
. Those option however will cause a change in the timestamp of some file. If you're working on a large project where compilation can take a long time (our current project take half an hour to compile with distributed builds), this may not be optimal.
In this situation, you can use another repository to move the commit to the correct branch. First, you'll need to clone your current repository (this need to be done only once):
$ git clone /path/to/repository repository.clone
$ cd repository.clone
$ git remote add origin repository.clone
$ git fetch origin
Then in your current repository, you commit your changes:
$ cd /path/to/repository
$ git add path/to/modified/files
$ git commit -m 'Commit message'
On the other repository, you fetch the new commit, and move it to the correct branch:
$ cd ../repository.clone
$ git fetch origin
$ git checkout correct-branch
$ git reset --hard origin/correct-branch
$ git cherry-pick origin/current-branch
$ # resolve conflicts if any, commit with -c option in this case
$ git push origin correct-branch:correct-branch
Then on the original repository, you remove the temporary commit, and remove the associated modification (except if you want to keep them in both branches).
$ cd /path/to/repository
$ git reset HEAD^
$ # edit file and remove modifications moved to other branch
This is more complex and involve history rewriting, but when your project are really large, and compilation time is a limiting factor, it can be great to know the technique. Note that you can reuse the cloned repository, so there is no need to delete / recreate it each time (if compilation time is long, then repository is probably large, and cloning it can take some time).