Search code examples
gitgit-stash

git-stash changes without reverting


I work on a project using Git. Every once in a while I find myself wanting to save my changes, without committing them, just as a backup, and then continue working. What I usually do is git stash and then immediately git stash apply to bring the code back to the same state as before stashing. The problem I have with this is that git stash reverts my work directory so even though I apply the stash immediately files and projects have to be rebuilt because they appear to have changed. This is quite annoying because some of our projects take ages to build.

So my question is, is there a way to stash my changes without reverting? If stash doesn't do that, is there any other command in git that can do it? Thank you.


Solution

  • When I posted this question I was new to git and didn't understand its power in full. Now I realize that stashing is not what I needed and that git's local branches do the job much better.

    Assume you are on main_branch, which you want to keep clean from experimental changes.

    Simply create a new branch in order to store your experimental changes.

    git checkout -b temp_branch
    

    Assume you do some changes and want to save your progress. Simply commit, nothing to worry about, it's all on the temp_branch:

    git commit -a -m "first change"
    

    Assume you do some more changes and want to store again:

    git commit -a -m "second change"
    

    Finally, assume you are happy with your experimental changes and want to merge them to the main branch. There are two cases:

    1) If you want to merge all changes, do:

    git fetch . temp_branch:main_branch
    

    This brings all changes of temp_branch into the main_branch, without switching to the main branch, which means your files are not modified and no recompilation is required. Note it's possible only if you haven't done any other changes on main_branch in the meantime. If main_branch has changed you need to use git merge or git rebase, but this scenario is beyond what the question is asking.

    2) Assume you want to merge only some of the commits of temp_branch into main_branch. You can do this with git cherry-pick. First do git checkout main_branch to switch to the main_branch (this modifies the files but this is inevitable since you are dropping some of your changes), then do git cherry-pick <SHA> (where <SHA> is the hash of the commit you want to merge). You can see the list of commits by doing git log temp_branch. Note that merging only some of the changes might give conflicts which you 'll need to resolve.