Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch to another branch without changing the workspace files

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.

like image 355
amorfis Avatar asked Dec 27 '11 23:12

amorfis


People also ask

Does switching branches change files?

So if you switch to a different branch and there are no files in the commit that were added to different commit you can: Merge the other branch into the current. That brings all changes from the branch being merged — new files a re added, updated files updated, removed files removed.

Can I change branch with uncommitted changes?

You may switch branches with uncommitted changes in the work-tree if and only if said switching does not require clobbering those changes.


2 Answers

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:

git checkout cleanchanges git merge --squash master git commit -m "nice commit comment for all my changes" 

(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 and cleanchanges. 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.

like image 162
Greg Hewgill Avatar answered Oct 04 '22 20:10

Greg Hewgill


Git. Switch to another branch

git checkout branch_name 
like image 45
Surendra Kumar Ahir Avatar answered Oct 04 '22 20:10

Surendra Kumar Ahir