DEV Community

Jeongho Son
Jeongho Son

Posted on

How to Undo git add / git commit / git push

Goal:

  • Be able to undo git add.
  • Be able to undo git commit.
  • Be able to undo git push.
  • Be able to delete untracked files.
  • Be able to restore modified files back to their original state before changes.

Undo git add (Unstage Files)

  • When you accidentally add files to the staging area that you didn’t intend to include:
  • You can remove files from the staging area without deleting your actual changes.
# First, check the file status
$ git status

# To unstage a specific file
$ git reset HEAD <file_name>

# To unstage all files from the staging area
$ git reset HEAD

Enter fullscreen mode Exit fullscreen mode

Undo git commit

  • When you accidentally committed files you didn’t intend to:
  • If you forgot to include certain files and committed too early.
# Check commit history
$ git log

# 1. Undo the commit but keep the changes staged (as if `git add` was done)
$ git reset --soft HEAD^

# 2. Undo the commit and unstage the changes (files remain in the working directory)
$ git reset --mixed HEAD^  # --mixed is the default, so you can omit it

# 3. Undo the commit and discard all changes (files will be deleted)
$ git reset --hard HEAD^

# If you want to reset your working directory to the latest commit from the remote (not recommended)
$ git reset --hard HEAD

Enter fullscreen mode Exit fullscreen mode

Undo git push

  • If you're not working on a shared repository, it's usually fine. But if you're collaborating with others, always discuss with your teammates before undoing a push.

Reason:
Commits made after the one you're reverting will be lost.

  • Personally, I try to avoid canceling a push.
    Instead, I prefer modifying the files and committing the changes again.

  • That way, the edit history is preserved and it's easier for teammates to track what was fixed.

# 1. Undo the latest commit
$ git reset HEAD^

# 2. Check the commit history
$ git log

# 3. Reset the working directory to a specific commit
$ git reset <commit_id>

# 4. After making necessary changes, force push to the remote repository (force push will overwrite remote history)
$ git push -f origin <branch_name>
Enter fullscreen mode Exit fullscreen mode

Appendix 1: Deleting Untracked Files

  • For some reason, untracked files tend to pile up while working... Since I can't stand messy workspaces, I clean them up pretty often
# Delete untracked files
$ git clean -f

# Delete untracked files and directories
$ git clean -f -d

# Delete untracked files, directories, and ignored files
$ git clean -f -d -x

Enter fullscreen mode Exit fullscreen mode

Appendix 2: Changing Commit Messages

  • If you wrote the wrong commit message, you can change it using the following command:
git commit --amend
Enter fullscreen mode Exit fullscreen mode

Top comments (0)