I cloned a git repository from GitHub, made some changes and some commits; I made quite a lot and all are quite dirty, so they're not suitable for a pull request. Now I created the branch cleanchanges
from origin/master
, so it's clean, and I want to commit my changes there as one commit with a nice commit comment.
When I am on the local master, I want to switch to my cleanchanges
but without changing the files. And then I'm able to commit.
How can I switch branches without changing files?
I want to make it clear: I have all the changes committed in the local master
. There are no uncommitted changes.
Simplest way to do is as follows:
Git. Switch to another branch
Why not just
git reset --soft <branch_name>
?Demonstration:
Result:
One thing to note though, is that the current branch changes to
original
. You’re still left in the previous branch after the process, but can easilygit checkout original
, because it’s the same state. If you do not want to lose the previousHEAD
, you should note the commit reference and dogit branch -f <previous_branch> <commit>
after that.The best bet is to stash the changes and switch branch. For switching branches, you need a clean state. So stash them, checkout a new branch and apply the changes on the new branch and commit it
Edit: I just noticed that you said you had already created some commits. In that case, use
git merge --squash
to make a single commit:(Edit: The following answer applies if you have uncommitted changes.)
Just switch branches with
git checkout cleanchanges
. If the branches refer to the same ref, then all your uncommitted changes will be preserved in your working directory when you switch.The only time you would have a conflict is if some file in the repository is different between
origin/master
andcleanchanges
. If you just created the branch, then no problem.As always, if you're at all concerned about losing work, make a backup copy first. Git is designed to not throw away work without asking you first.
Another way, if you want to create a new commit instead of performing a merge:
The first (hard) reset will set your working tree to the same as the last commit in
master
.The second reset will put your HEAD back where it was, pointing to the tip of the
cleanchanges
branch, but without changing any files. So now you can add and commit them.Afterwards, if you want to remove the dirty commits you made from
master
(and assuming you have not already pushed them), you could:This will discard all your new commits, returning your local
master
branch to the same commit as the one in the repository.