Reverting to an old commit & Grabbing changes from another branch : git checkout


Nitin Venkatesh's Gravatar

Nitin Venkatesh
published March 21, 2014, 11:47 a.m.


You might have seen me blogging regularly the last three weeks. That's thanks to James Clear's advice on forming new habits. I am trying to keep the "blog every saturday morning" habit this week with a short post on things I learnt to do with Git's Checkout command. So here we go!

Reverting to an old commit

To revert back to an old commit, like say 5 or so commits back, doing git-revert twenty times isn't a great solution. I don't mind having my mistakes out in the public, so it's git-checkout to the rescue! The syntax to revert to an old commit is simple - git checkout <commit-hash> .

$ git status
# On branch gh-pages
nothing to commit, working directory clean

$ git log --oneline
1333bca Updates Atom feed
9b8fae0 Fixes feed
38eef03 Adds tags insted of markdown
de53e1f Changes in License

To rollback to a previous commit like de53e1f, the last commit you see above, I'd do git checkout de53e1f .

$ git checkout de53e1f .
$ git status
# On branch gh-pages
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#   modified:   _data/props.yml
#   modified:   blog/feed.xml
#   modified:   docs.html
#

And after committing my work, I can see that the file has been rolled back to a previous commit along with the evidence of the mistakes I committed.

$ git log --oneline
be2fea5 Rollsback to previous commit
1333bca Updates Atom feed
9b8fae0 Fixes feed
38eef03 Adds tags insted of markdown
de53e1f Changes in License

<hr />

Grabbing changes from another branch

It's as simple as git checkout <branch-name> <file-name> to grab a file from another branch, or replace your existing file with the one in the other branch.

$ git checkout master blog/feed.xml
$ git status
# On branch gh-pages
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#   modified:   blog/feed.xml
#