How to revert your last commit without losing any change?

Outline * Introduction * Scenario * Solution * Conclusion * References Introduction Have you ever committed something but realised that you forgot to add a file or added a file that you shouldn’t have? This post will look at how to revert your last commit without losing your changes. Scenario Imagine you’re working with different files in a project but you want to commit a single one of them. You add your changes and commit the file; however, you realise that you have also committed anot

Abdallah Yashir
2 min readNov 10, 2023

Outline

  • Introduction
  • Scenario
  • Solution
  • Conclusion
  • References

Introduction

Have you ever committed something but realised that you forgot to add a file or added a file that you shouldn’t have?

This post will look at how to revert your last commit without losing your changes.

Scenario

Imagine you’re working with different files in a project but you want to commit a single one of them. You add your changes and commit the file; however, you realise that you have also committed another file that you shouldn’t.

How do you revert this without losing any change esp. the other file you’ve committed?

Solution

The simplest solution is to use the git reset command.

git reset --soft HEAD~1

Or

git reset --soft HEAD^

The --soft flag will reset the commit but leave the changes in your files.

The HEAD~1 or HEAD^ will reset the last commit.

Conclusion

In this post, we looked at how to revert your last commit without losing your changes. This is extremely important when working on complex projects as you don’t want to lose any changes you’ve made — while still being able to modify your commit history.

Other ways to do the same include:

  • git revert
  • git amend
  • git rebase

References

git-reset

git-reset

Stack-Overflow

If you have any questions regarding this post, please feel free to contact me on Twitter or LinkedIn. I am always happy to hear from you.

--

--

Abdallah Yashir

Senior Software Developer, Writer, Amateur Photographer, Reader