12

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.

1

6 Answers 6

15

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>}

3

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

1
3

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

2

Using the command line, short answer:

git stash
git checkout otherBranch

If the brach is in origin use:

git checkout origin otherBranch

..
do your changes/commits
..
git stash apply

With git stash apply you get back your previous changes. You could find merge conflicts...fixed them and commit again.

1

You can stash your branches. Here is an example: http://www.gitguys.com/topics/temporarily-stashing-your-work/

2
0

Can't you just create another directory and clone the desired branch into it?

If you have a runtime configured to use particular directory, make it a link to the branch clone directory you are currently working with. This way you could have more than one branch locally without much reshuffling of your local resources (just a plain script to re-link directory used by your runtime/server).

Not the answer you're looking for? Browse other questions tagged or ask your own question.