How do i undo my change in a git file?



  • git man page: http://bit.ly/2nvGNWB

    Let's say you made a change to a file and committed it, and now you want to undo the change.

    Here's all your changes and the diff between current and previous commit, i.e. before you added the Fifth line, and you now want to undo the Fifth line.

    $ git log --oneline
    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
    
    $ git diff 08c6bb5
    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
    

    You use the git checkout command, which moved the HEAD to a position where you are happy with the file contents.

    Remember you can use the commit hash or the HEAD~<number> to get to the commit you want

    $ git checkout 08c6bb5 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
    

    NOTE: Be careful when doing checkouts, if you get the file names or hash numbers wrong or do not provide a file name to checkout, you can end up in what's know as a detached HEAD state.

    You can see you're back to where the Fifth line did not exist. Git behind the scenes just made a new commit of the file, you can observe this by doing a git status

    Before checkout the git status would have shown nothing to commit, and clean working directory

    $ git status
    On branch master
    Changes to be committed:
      (use "git reset HEAD <file>..." to unstage)
    
    	modified:   README.md
    

    and diff shows a line being deleted from our file, instead of pluses symbols we got minus symbols now, showing the line(s) deleted.

    $ git diff --staged
    diff --git a/README.md b/README.md
    index 9f28333..4ba7d0a 100644
    --- a/README.md
    +++ b/README.md
    @@ -5,5 +5,3 @@ 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
    

    and not just commit your file.

    $ git commit -m "I didn't mean to add the last line, so deleted it"
    [master f1f04a2] I didn't mean to add the last line, so deleted it
     1 file changed, 2 deletions(-)
    

Log in to reply
 

© Lightnetics 2024