Search code examples
gitgit-checkoutgit-stash

What is the difference between git-stash and git-checkout?


I try to go from one local branch to another one. Git tells me that I cannot do it because my local changes to the following files would be overwritten by checkout.

Then I get a "recommendation" Please, commit your changes or stash them before you can switch branches.

I know that I do not need the changes to the mentioned file. It is OK to overwrite them. So, I try to stash. I execute git stash file_name. As a result I get:

Usage: git stash list [<options>]
   or: git stash show [<stash>]
   or: git stash drop [-q|--quiet] [<stash>]
   or: git stash ( pop | apply ) [--index] [-q|--quiet] [<stash>]
   or: git stash branch <branchname> [<stash>]
   or: git stash [save [--patch] [-k|--[no-]keep-index] [-q|--quiet]
               [-u|--include-untracked] [-a|--all] [<message>]]
   or: git stash clear

OK. It does not work. Then I try git checkout file_name. No complains from git. Then I can switch from one branch to another one. So, it seems that I got what I needed (go to the second branch without saving changes to the first branch).

However, I would like to ask why stash did not work, and how the final result would be different in case it had worked?


Solution

  • You cannot stash a single file explicitly. Had you run git-stash it would have stashed all your modifications.

    git checkout -- file discards your changes to that file in working dir and checkout the version of that file recorded by the current commit (i.e. the one that HEAD points to).