Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cancel a local git commit?

My issue is I have changed a file e.g.: README, added a new line 'this for my testing line' and saved the file, then I issued the following commands:

git status  # On branch master # Changed but not updated: #   (use "git add <file>..." to update what will be committed) #   (use "git checkout -- <file>..." to discard changes in working directory) # #   modified:   README # no changes added to commit (use "git add" and/or "git commit -a")   git add README  git commit -a -m 'To add new line to readme' 

I didn't push the code to GitHub. Now I want to cancel this commit.

For this, I used

git reset --hard HEAD~1 

But I lost the newly added line 'this for my testing line' from the README file. This should not happen. I need the content to be there. Is there a way to retain the content and cancel my local commit?

like image 362
Amal Kumar S Avatar asked Jan 31 '11 12:01

Amal Kumar S


People also ask

How do I undo a local commit?

The easiest way to undo the last Git commit is to execute the “git reset” command with the “–soft” option that will preserve changes done to your files. You have to specify the commit to undo which is “HEAD~1” in this case. The last commit will be removed from your Git history.

How do I cancel an outgoing commit?

Open the history tab in Team Explorer from the Branches tile (right-click your branch). Then in the history right-click the commit before the one you don't want to push, choose Reset. That will move the branch back to that commit and should get rid of the extra commit you made.


2 Answers

Just use git reset without the --hard flag:

git reset HEAD~1 

PS: On Unix based systems you can use HEAD^ which is equal to HEAD~1. On Windows HEAD^ will not work because ^ signals a line continuation. So your command prompt will just ask you More?.

like image 150
Koraktor Avatar answered Sep 18 '22 12:09

Koraktor


Use --soft instead of --hard flag:

git reset --soft HEAD^ 

It will remove the last local (unpushed) commit, but will keep changes you have done.

like image 44
TpED Avatar answered Sep 17 '22 12:09

TpED