Today I got a better understanding of how git works, in particular what git checkout
and git reset
do.
7153617ff70e716e229a823cdd205ebb13fa314d
.HEAD
is pointing to a branch.git checkout <commit> <paths>
… tells Git to replace the current state of paths
with their state in the given commit
.
paths
can be one or more files or directories.HEAD
commit.
git checkout <path>
restores path
from your last commit. It is a 'filesystem-undo'.path
is given, git moves HEAD
to the given commit
(thereby changing the commit you're sitting and working on).
git checkout branch
means switching branches.git checkout HEAD~2 app/models/foo.rb
… drops all modifications of foo.rb
and replaces the file with its version from HEAD~2
= two commits before the current.
git reset <commit>
… re-sets the current pointer to the given commit
.
HEAD
and this branch are moved to commit
.
HEAD
is still pointing to initial the branch and the branch is now pointing towards the commitdetached HEAD
state, git reset
does only move HEAD
. To reset a branch, first check it out.
You are currently working upon commit 123abc
. After resetting to a previous commit xyz789
(e.g. with git reset HEAD~2
), you have no easy access to commit 123abc
anymore, because HEAD
and the branch are both pointing to xyz789
. This will result in staging the commited files from 123abc
and keeping the files in the current index.
To move the branch pointer 'back to the front', you can't use git checkout
, as it only moves HEAD
. You have to reset your branch to that commit: git reset 123abc
. (If you didn't save the first commit's hash (123abc
), git reflog
will help you finding it.)