Temporarily switch working copy to a specific Git commit

GitCommitTemporary

Git Problem Overview


How to switch to specific Git commit without losing all the commits made after it?

I want that local files will be changed, but commits' database will remain intact, only the current position pointer is set to currently selected commit.

I want to change files' state to specific commit, run project and, when finished, restore files back to last commit.

How to do this without zipping the whole project's folder?

Git Solutions


Solution 1 - Git

If you are at a certain branch mybranch, just go ahead and git checkout commit_hash. Then you can return to your branch by git checkout mybranch. I had the same game bisecting a bug today :) Also, you should know about git bisect.

Solution 2 - Git

First, use git log to see the log, pick the commit you want, note down the sha1 hash that is used to identify the commit. Next, run git checkout hash. After you are done, git checkout original_branch. This has the advantage of not moving the HEAD, it simply switches the working copy to a specific commit.

Solution 3 - Git

In addition to the other answers here showing you how to git checkout <the-hash-you-want> it's worth knowing you can switch back to where you were using:

git checkout @{-1}

This is often more convenient than:

git checkout what-was-that-original-branch-called-again-question-mark

As you might anticipate, git checkout @{-2} will take you back to the branch you were at two git checkouts ago, and similarly for other numbers. If you can remember where you were for bigger numbers, you should get some kind of medal for that.


Sadly for productivity, git checkout @{1} does not take you to the branch you will be on in future, which is a shame.

Solution 4 - Git

I once implemented git checkout @{10} and was working fine, then suddenly my jumbo cup of caramel coffee fell on the PC and....

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPaulView Question on Stackoverflow
Solution 1 - GitAlexander PavlovView Answer on Stackoverflow
Solution 2 - GitFemarefView Answer on Stackoverflow
Solution 3 - GitBenjohnView Answer on Stackoverflow
Solution 4 - Gitmchrgr2000View Answer on Stackoverflow