Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to undo a git commit without losing my files? [duplicate]

Here's something that regularly happens to me at work:

[user@macmini ~/code/project $] git add .
[user@macmini ~/code/project $] git commit -m "Fixed whatever bug"
[master 93a3c47] Fixed whatever bug
 3 files changed, 290 insertions(+)
 create mode 100644 .DS_Store
 create mode 100755 some-code.js
 create mode 100755 some-other-code.js

As you can see, I've accidentally committed the .DS_Store file which macOS like creating after you open a folder in Finder.

In this case I usually clone the repo again, copy and paste my new code in, and commit again without the .DS_Store. But I know it's not the clean way to do it.

So, how can I cleanly undo a commit? I've tried git reset --hard HEAD but it deletes my new files too.

like image 630
Chef Tony Avatar asked Dec 16 '18 19:12

Chef Tony


People also ask

Can I undo my commit in git?

The git revert command is used for undoing changes to a repository's commit history. Other 'undo' commands like, git checkout and git reset , move the HEAD and branch ref pointers to a specified commit. Git revert also takes a specified commit, however, git revert does not move ref pointers to this commit.


1 Answers

git reset HEAD~1

This will "undo" your last commit without touching your working directory (any our files). It is the same as git reset --mixed HEAD~1. You can also do git reset --soft HEAD~1, which will leave all the files as marked for commit.

If you mostly like your commit, but just want to make a small change to its content or its commit message, you can amend the current commit instead:

git rm .DS_Store
git commit --amend

This will prompt you for editing the commit message (you may leave it unchanged), and will then modify the commit with your changes.


git reset basically means "move my current branch to the given commit", and HEAD~1 means "the previous commit". The only problem with your command was that it included --hard, which says "oh, also make all my files look like they did in that commit".

A branch is just a label that references a particular commit; it can be freely moved around (although if you've pushed a branch and you move it backwards, you'll get problems when you try to push or pull).

If you ever feel the need to re-clone a repository, there is almost always a better solution in git. Commits in git, and the files in them can be undone, redone, moved, and sometimes even resurrected. Also, commits are local: no one sees them until you've pushed.

like image 53
Aasmund Eldhuset Avatar answered Oct 02 '22 02:10

Aasmund Eldhuset