skip to Main Content
  • When to undo a commit and when to revert a commit in git?
  • What are the git commands to do both of them?
  • How to perform both tasks using VS code (UI)?

2

Answers


  1. Chosen as BEST ANSWER

    A-undo commit (most recent(s))

    undo commit-> You want your commit back
    

    enter image description here

    Git commands:

    To undo a local commit in Git, you can use the git reset command.

    Types/Options:

    1. --mixed (default)
    2. --soft
    3. --hard

    1. --mixed: undo commit + unstaged the changes and puts them back into the working directory.

    git reset HEAD~ 
    

    or

    git reset –mixed HEAD~1  //1-> undo one most recent commit
    

    or

    git reset –mixed HEAD~2  //2-> undo two most recent commit
    

    2. --soft: undo commit + keep the changes in the staging area (index).

    git reset --soft HEAD~ 
    

    3. --hard: undo commit + discard/remove all the changes.

    git reset --hard HEAD~ 
    

    Note1: In all the reset commands, the branch pointer of your current branch will be moved to the previous commit (HEAD~ refers to the commit before the current one) as shown in the above image. Now if you want your changes in :

    • the working directory use --mixed option,
    • the staging area (index) use --soft option, and
    • for discard/remove changes use --hard option.

    Note2: Undo commit **DOES NOT** creates a new commit.

    Note3: You should undo commit(s) if your commit(s) is/are local, means you did not pushed into remote.

    B-revert commit

    revert commit-> You want your commit back but in a new commit
    

    enter image description here

    Git commands:

    To undo a published/remote commit in Git, you can use the git revert command.

    Types/Options:

    1. --edit (default) : soft revert
    2. --no-edit :hard revert

    1. --no-edit: undo commit + creates a new commit (changes discarded in this commit)

    git revert commit-id/commit hash
    

  2. Undo is to ditch last commit. It will not exists anymore in the current branch.

    Command(s depending on how it is implemented in VSCode):

    git reset --soft HEAD~
    

    Or (to not keep changes in staging area):

    git reset --mixed HEAD~
    

    Revert is creating a new commit that contains all the opposite changes of the commit you will revert. So original commit and new reverting commit are in the current branch.

    Command:

    git revert <HASH_COMMIT_TO_REVERT>
    

    Both strategies have pros and cons. Read about it.
    The main idea is if it’s to fix an error just made and the commit has still not been pushed, undo is perfectly fine.
    If commit/history has been pushed, except special cases, revert is more likely the way to go…

    PS: another solution instead of undo could be just to amend the last commit…

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search