Wednesday, March 20, 2019

Git: undo the most recent commits


Use the command git revert to revert several most recent commits.

For example, we have a file name onefile with 4 commits.

$ git log
commit 5a289042bb5d90c2780b0c55a34879f6853cc495
Author: JL <jl@solezero.com>
Date:   Wed Mar 20 19:04:07 2019 -0400

    D4

commit cc2c4931fc2c0422c26557801104d2924a568617
Author: JL <jl@solezero.com>
Date:   Wed Mar 20 19:03:54 2019 -0400

    C3

commit a0c17ecd71a595e3ae4fee92f72fc50d8797e898
Author: JL <jl@solezero.com>
Date:   Wed Mar 20 19:03:31 2019 -0400

    B2

commit 4f0f011379740c959cac1da2355f56c6de8b5523
Author: JL <jl@solezero.com>
Date:   Wed Mar 20 19:03:13 2019 -0400

    A1


If we want to remove the 2 most recent commits and go back to commit a0c17ecd71a595e3ae4fee92f72fc50d8797e898 (with comments B2), we can run the command:

$ git revert --no-edit a0c17ecd71a595e3ae4fee92f72fc50d8797e898..HEAD

With the option --no-edit, we are not prompted to input comments for every commit being reverted.

New commits are automatically added to revert the last 2 changes.

$ git log
commit 1a705ec2d7fffa5ebb57724372f41ccd3e228a5c
Author: JL <jl@solezero.com>
Date:   Wed Mar 20 19:19:23 2019 -0400

    Revert "C3"

    This reverts commit cc2c4931fc2c0422c26557801104d2924a568617.

commit 9e34a2cfac47034ecc28a1f0f71d60d413bc6055
Author: JL <jl@solezero.com>
Date:   Wed Mar 20 19:19:23 2019 -0400

    Revert "D4"

    This reverts commit 5a289042bb5d90c2780b0c55a34879f6853cc495.

commit 5a289042bb5d90c2780b0c55a34879f6853cc495
Author: JL <jl@solezero.com>
Date:   Wed Mar 20 19:04:07 2019 -0400

    D4

commit cc2c4931fc2c0422c26557801104d2924a568617
Author: JL <jl@solezero.com>
Date:   Wed Mar 20 19:03:54 2019 -0400

    C3

commit a0c17ecd71a595e3ae4fee92f72fc50d8797e898
Author: JL <jl@solezero.com>
Date:   Wed Mar 20 19:03:31 2019 -0400

    B2

commit 4f0f011379740c959cac1da2355f56c6de8b5523
Author: JL <jl@solezero.com>
Date:   Wed Mar 20 19:03:13 2019 -0400

    A1


We can verify that the current version is the same as the commit a0c17ecd71a595e3ae4fee92f72fc50d8797e898 (B2)

$ git diff a0c17ecd71a595e3ae4fee92f72fc50d8797e898


No comments:

 
Get This <