How do i revert a file back to a previous commit in git?



  • Similar to the way you can run git diff on various commits: https://lightnetics.nodebb.com/topic/926/how-do-i-look-at-differences-between-different-commits-in-git you can also get back to a specific commit using the git checkout

    If i want to go back one commit.

    Let's see what I have now:

    $ git status
    On branch master
    nothing to commit, working directory clean
    $ cat README.md 
    First Line: Today i woke up and went running
    
    Second Line: When I get back from running I'm tired
    
    Third Line: I got straight to bed
    
    Fourth Line: and I dream of running the marathon
    

    Show all my commits

    $ git log --oneline
    f1f04a2 I didn't mean to add the last line, so deleted it
    cc9e080 I want to keep the changes to my fith line
    08c6bb5 My Super duper forth line message
    afa0b05 More than one line this is another line
    dbaade7 Added a second line to my file
    2561e02 Initial commit of repository
    

    I want to go back to the one where I have my Fifth line back in the file.

    $ git checkout HEAD~1 README.md
    $ git status
    On branch master
    Changes to be committed:
      (use "git reset HEAD <file>..." to unstage)
    
    	modified:   README.md
    
    $ cat README.md 
    First Line: Today i woke up and went running
    
    Second Line: When I get back from running I'm tired
    
    Third Line: I got straight to bed
    
    Fourth Line: and I dream of running the marathon
    
    Fifth Line:  but I don't dress up in a silly costume I'm a serious runner
    

    As we have reverted back to a previous commit, the status show modified and ready to commit, the colour, of the modified are either red or green, (although this text does not show it) this is green, meaning, it's staged already and ready to commit, if it had not been staged the modified text would be red.

    The git diff shows the current and the staged differences

    $ git diff --staged
    diff --git a/README.md b/README.md
    index 4ba7d0a..9f28333 100644
    --- a/README.md
    +++ b/README.md
    @@ -5,3 +5,5 @@ Second Line: When I get back from running I'm tired
     Third Line: I got straight to bed
     
     Fourth Line: and I dream of running the marathon
    +
    +Fifth Line:  but I don't dress up in a silly costume I'm a serious runner
    

Log in to reply
 

© Lightnetics 2024