Reputation: 3
First of all I'm new to web development in general and so let me know if I make any obvious mistakes.
So I decided that if I want to start making websites I'm probably going to need to learn Git and GitHub.
I currently understand how to initialize a repository, stage and commit and push it all to a GitHub page. What I'm struggling with now is the process of reverting back to an old commit. So lets say I've made two commits called commit 1, commit 2 respectively.
If I'm on commit 2 how to I go back to commit 1?? Can I go back to commit one change code commit the changes and still go back to commit 2 after?? What specifically happens to the code and files when moving between commits.
Please feel free to talk to me like a 5 year old who understands nothing to do with Git and the command line. Thanks in advance guys.
Upvotes: 0
Views: 88
Reputation: 6476
You can use the reset
command to navigate over the history. See how easy it is, at first let's create two files:
$ touch a
$ touch b
Let's commit one of them:
$ git add a
$ git co -m "First commit"
[master d263314] First commit
1 file changed, 0 insertions(+), 0 deletions(-)
create mode 100644 a
Let's commit the other one:
$ git add b
$ git co -m "Second commit"
[master 16aa86a] Second commit
1 file changed, 0 insertions(+), 0 deletions(-)
create mode 100644 b
Now let's check the history out:
$ git log --oneline
16aa86a Second commit
d263314 First commit
38df137 Initial commit
As you can see there are three commits and they have hash codes to distingush them.
There is a special pointer that points at the commit that is on top of the history. It is called HEAD
. When the a
file was committed HEAD pointed at this commit, but when the second file was committed HEAD started to point at the second commit.
The reflog
command helps you to track history where HEAD pointed.
$ git reflog
16aa86a HEAD@{0}: commit: Second commit
d263314 HEAD@{1}: commit: First commit
38df137 HEAD@{2}: commit (initial): Initial commit
In order to get rid of the most recent commit, you need to make HEAD point at one of the previous commits. This is when the reset
command appears.
$ git reset --hard HEAD@{1}
HEAD is now at d263314 First commit
Be carefull, all your unstaged data gets lost. Let's check the history out:
$ git log --oneline
d263314 First commit
38df137 Initial commit
But it is possible to jump not only to one of previous commits, it is possible to jump at any commit as well, let's get back to the second commit:
$ git reset --hard 16aa86a
HEAD is now at 16aa86a Second commit
Let's check the history out:
$ git log --oneline
16aa86a Second commit
d263314 First commit
38df137 Initial commit
As you can see the history gets restored
Get some time and read this amazing book I guarantee you will become a highly expirienced Git user
Upvotes: 1