Here is a simple recipe for restoring a file to its state in a prior commit in git using git-checkout
(unlike the effects of git-revert
or git-reset
):
$ git init
Initialized empty Git repository
$ echo "1" > count
$ cat count
1
$ git add 1
$ git status
On branch master
No commits yet
Changes to be committed:
(use "git rm --cached <file>..." to unstage)
new file: count
$ git commit -m 'Count is 1'
[master (root-commit) 9687be0] Count is 1
1 file changed, 1 insertion(+)
create mode 100644 count
$ echo "2" > count
$ cat count
2
$ git commit -am 'Count is 2'
[master 66d5892] Count is 2
1 file changed, 1 insertion(+), 1 deletion(-)
$ git log
* 66d5892 - (HEAD -> master) Count is 2
* 9687be0 - Count is 1
Now this file has two commits. To restore the contents of ‘count’ to ‘1’, use checkout
with its commit id/checksum:
$ git checkout 9687be0 count
$ git status
On branch master
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
modified: count
$ cat count
1
$ git commit -m 'Count is 1 again'
[master 61ca945] Count is 1 again
1 file changed, 1 insertion(+), 1 deletion(-)
$ git lg
* 61ca945 - (HEAD -> master) Count is 1 again
* 66d5892 - Count is 2
* 9687be0 - Count is 1
Note that this is adding a new commit, unlike the effect of git reset, but if it is necessary to preserve the commit history (and not affect other devs), this would be an option.