Search code examples
gitgit-checkout

Git: return to last version after returning to an old version for testing


I'm developing a program and use Git to save versions of it, using git commit.

I wanted to test an old version of my program, so I went back to this version using git checkout id-of-the-commit. I modified a file there simply to change the names of the input files to process with this old version of my program.

Now that I get the results I wanted with my old program, I'd like to go back to the last version of my program. So I tried git checkout master. This returns an error:

$ git checkout master
error: Your local changes to the following files would be overwritten by checkout:
    code/launch_program.sh
    code/__pycache__/feature.cpython-310.pyc
Please, commit your changes or stash them before you can switch branches.
Aborting

I'm very new in Git and have trouble to find an answer to my question mainly because I don't understand all the Git jargon.


Solution

  • Keep in mind that a branch, like master, is merely a string pointing to a particular commit. When you said git checkout <the-id>, you did not move the master branch pointer; you are now not on any branch, a state that Git calls "detached head" (and you would have seen this in Git's responses to you).

    This is fine, but you can't do any real work (i.e. work that you intend to keep) without being on a branch, so if you are just playing around (experimenting), when you're done, you just want to get back to master. To do that, instead of git checkout master, say:

    git reset --hard
    

    That means: "OK, Git, I'm done fooling around here experimenting with the past; throw away my experiments and put me back on master!"

    If, on the other hand, you had wanted to keep the results of your experiments and incorporate them into master, then you would add-and-commit them, make a branch to point to them, go back to master, and cherry-pick that commit onto the end of master:

    git add .
    git commit -m 'a useful experiment'
    git branch temp
    git switch master
    git cherry-pick temp