Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch branch without committing the working code

Tags:

git

I'm using git for source code repository and the current code in a messy state and want to switch to other branches for a bit of work. The issue is that I don't want to do a commit of half-done work just, so how can I get back to this point later.

like image 872
Sachin Kumaram Avatar asked Feb 25 '16 10:02

Sachin Kumaram


3 Answers

You can use git stash to "discard" changes for a while and then, when you want to restore your previous changes use git stash pop*

You can also (and is safer) commit your WIP (Work In Progress) work, switch to another branch, do your work, switch back to original branch, finish original work and then squash your commits into just one.
Remember that commit isn't equal to pushing, so you can locally have a messy history but, once rebased and squashed, you (and your team) will only see the clean version.

*pay attention because if you stash more than one time, git pop will pop only last stash. In this case you need to use git pop stash@{<revision>}

like image 112
DonCallisto Avatar answered Oct 11 '22 20:10

DonCallisto


You have two option to do this.

Option 1: - Create the patch for the working code and checkout that all the working code then switches into the another branch.

Option 2:- You can stash your branches. Click here for more detail example: https://www.atlassian.com/git/tutorials/saving-changes/git-stash

like image 3
Samir Avatar answered Oct 11 '22 22:10

Samir


If you have the newer git (>=ver.2.5.0), you can use git worktree.

By the following command, you can checkout a temporary worktree to use.

git worktree add sourcetree_dir branch_name

After finished your work on this branch , you can use the following command to delete it.

git worktree prune

like image 3
gzh Avatar answered Oct 11 '22 22:10

gzh