Actions

EmSys

Git - Undoing Staged Changes - before committing

From EdWiki

GitLab - Undoing Staged Changes (before committing)

  • Goals
    Learn how to revert changes that have been staged
  • Change the file and stage the change
    Modify the hello.c file to have a bad comment
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[]) {
    if( argc > 1 ) {
        puts("Hello ");
        puts(argv[1]); /* This is an unwanted but staged comment */
    } else {
        puts("Hello World!!!"); /* prints !!!Hello World!!! */
    }
    return EXIT_SUCCESS;
}

And then go ahead and stage it.

git add hello.c
  • Check the Status
    Check the status of your unwanted change.
git status

The status output shows that the change has been staged and is ready to be committed.

git reset HEAD hello.c

The reset command resets the staging area to be whatever is in HEAD. This clears the staging area of the change we just staged.

The reset command (by default) doesn’t change the working directory. So the working directory still has the unwanted comment in it. We can use the checkout command of the previous to remove the unwanted change from the working directory.

  • Checkout the Committed Version
git checkout hello.c
git status

And our working directory is clean once again.