4

I tried to delete my last commit. I thought that git checkout followed by the hash of the commit would replace my current code with the code of the commit. This didn't work and I get now a message which says Nothing to commit, working tree clean. How can I get rid of this message and delete my last commit?

Elias Dolinsek
  • 669
  • 3
  • 7
  • 11
  • `git checkout ` is the front end command for *extracting* a commit into the staging-area and work-tree. Why would you expect this to *delete* a commit? (This is a real question, by the way—it seems likely that some bad advice led to the conclusion.) Commits can't exactly be deleted, but you can get the effect you want in some (many) cases using `git reset`. – torek Jul 22 '18 at 17:27
  • Check this https://stackoverflow.com/questions/927358/how-to-undo-the-most-recent-commits-in-git/#927386 – Madhu Bhat Jul 22 '18 at 17:30
  • @MadhuBhat I wanted to reset my code the the last commit which shouldn't be deleted with that – Elias Dolinsek Jul 22 '18 at 17:33
  • So do you only want to undo your local changes and not your last commit? – Madhu Bhat Jul 22 '18 at 17:37
  • I thought that I can just continue where everything still worked, and then commit it – Elias Dolinsek Jul 22 '18 at 17:40
  • If you only want to remove all your local changes that haven't been committed yet, you need to use `git checkout .` – Madhu Bhat Jul 22 '18 at 17:41
  • Note that it would remove only unstaged local changes. – Madhu Bhat Jul 22 '18 at 17:43
  • Possible duplicate of [Throw away local commits in git](https://stackoverflow.com/questions/5097456/throw-away-local-commits-in-git) – phd Jul 22 '18 at 19:20

2 Answers2

3

By doing git checkout <hash> you went into so called "detached head" state, which in simple terms means you're not on any branch right now. If you want to return to your normal branch just do:

git checkout <branch name>

(where <branch name> can be any of master, develop, hotfix - it really depends how you name them and what flow you use to manage your development/release cycle... try git branch --list to get a list).

After that, if you want to delete the last commit you can do:

git reset --hard HEAD~1

but be very careful about the --hard switch as it will physically delete the most recent commit, which basically means it's unrecoverable (and I don't really remember if manipulating the reflog would help restore it in this situation).

TeHMoroS
  • 46
  • 2
0

You may want to check this StackOverflow question for more details, but it sounds like the repo doesn't know about your local branch. You need to set your remote repo by using:

git branch -u <upstream branch>

so if you're trying to push to master branch, use

git branch -u origin/master

Numilani
  • 346
  • 4
  • 16