Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do you need to create a branch to check out a specific git revision?

Tags:

A common thing I'd like to do is revert my working copy to a particular revision, do some testing, and then bring it back to the head of my current master. In the past I have naively done a "git checkout hash" only to lose my head. I've since learned I can create a branch and check that out, switch back and delete the branch, but it feels like too many steps for a simple check. In SVN parlance, is there a way to quickly revert and then quickly go back to the tip of trunk in git?

Edit: I think my confusion stems from the fact that when I checkout a hash and then git log, I don't see the changes that happened after the checked out hash (which is reasonable, when you think of it). But the accepted answer is correct; "git checkout branch" will restore the head to the previous branch.

like image 998
Nick Avatar asked May 11 '09 17:05

Nick


People also ask

Is it necessary to create a new branch in git?

You should create a new branch when you're doing development work that is somewhat experimental in nature. So in your scenario definitely create a new branch and not a folder within master. If you created your sandbox work as a directory in the master, it's going to reside there until you remove it using git.


2 Answers

Assuming you're already on a branch (which you always should be for changes you want to keep), you can just do

git checkout <revision to check out> 

This will take you off the topic branch you were working on into (no branch), in which the working copy refers directly to a commit ID rather than a branch name as normal.

Then to move back, simply:

git checkout <old branch name> 

A helpful way to think of it is this: git checkout never alters branches; it merely changes what your working copy is currently looking at (ie, HEAD), which might either be a branch (in which case commits will update the branch) or a random commit hash.

As such, as long as the changes you want to keep are on a branch, you don't have to worry about git checkout losing them.

like image 85
bdonlan Avatar answered Oct 25 '22 01:10

bdonlan


You can create a branch at the the specific commit you want to checkout (from the manual page)

git branch [--set-upstream | --track | --no-track] [-l] [-f] <branchname> [<start-point>] 

so fill in the <start-point> as the SHA1 you want you new branch <branchname> to start at and you won't get your 'head' detached from an expanding branch.

There will be other things you probably want to do to keep some of your working files in the state you desire....

like image 25
Philip Oakley Avatar answered Oct 25 '22 02:10

Philip Oakley