×

When you worked on a Git repository, sometimes you want to undo your last commit. Fortunately, Git has a special pointer called HEAD which points to the newest commit in the local branch you’re working on.

To undo a commit, you have to point the HEAD to the previous commit ID of the current working branch.

Also, If you are a web developer or a software engineer, it is very likely that you are pushing a lot of commits to your Git repository everyday.

However, in some cases, you committed some files that should not be pushed to your Git repository.

Sometimes, you may want to perform additional changes before issuing the commit.

As a consequence, you need to undo the last commit from your Git repository.

Here at LinuxAPT, as part of our Server Management Services, we regularly help our Customers to perform related Git queries.

In this context, we shall look into how to undo the last commit in Git.


How to Undo the Last commit in Git ?

You can use the following command to undo the changes in Git:

$ git reset <commit-id>

There are some additional arguments that come along with the git reset command:

i. –soft: Update the HEAD to a given commit while the current working directory and staging index are not changed.


ii. –mixed: Update the HEAD to a given commit and change the staging index to the specified commit while the current working directory is not changed. This option is the default operation when using the git reset command without any argument.


iii. –hard: Update the HEAD and change both of the current working directory and staging index to the specified commit. When using this option, bearing in mind that all the local changes you have not committed will be lost.


1. Soft reset

To avoid losing the changes you made on the current working directory and staging index when undoing the last commit, let’s run the following command:

$ git reset --soft HEAD~1

HEAD~1 means one commit before HEAD (the previous commit of the latest commit).

Before undoing the latest commit:

$ git log

After undoing the latest commit using the –soft option:

$ git reset --soft HEAD~1


2. Hard reset

If you don't want to keep the changes you made on the current working directory and local files that haven't been committed, run the git reset command with the –hard option:

$ git reset --hard HEAD~1

[Need urgent support in developing your Website? We are available to help you today. ]


Conclusion

More Linux Tutorials

We create Linux HowTos and Tutorials for Sys Admins. Visit us on IbmiMedia.com

Also for Tech related tips, Visit forum.outsourcepath.com or General Technical tips on www.outsourcepath.com