Discard Changes in Git

  1. Discarding One File in Git
  2. Discarding All Local Changes in Git
  3. Saving Changes on the Stash in Git

No matter how expert you are in programming, it’s not always sure that your code works on the first attempt. Fortunately, Git has the option that allows us to discard or undo any of your changes that you don’t want anymore in the code repository. It provides us with a secure network for our work.

This article will discuss various ways to discard changes in Git in the branch. Local changes in Git are explained as changes that have not been pushed yet to the local or remote repository.

Discarding One File in Git

For example, you want to discard some of the changes in the particular file, then the command that will fulfill this situation (discard this type of changes) is mentioned below.

git restore somefile.html

This will discard all uncommitted changes in our desired file. But the main point is that we should be cautious about these changes because once we discard them, we can’t get them back anyhow at any cost.

Discarding All Local Changes in Git

Git provides us with many options, one option is already mentioned above, and the other one we are explaining here.

Sometimes we want to discard all of the current changes that we have done in the code; for that purpose, we’ll use the parameter . with the command git restore instead of mentioning a file path with the command.

$ git restore.

Most of the time, we have untracked files in our working copy, and we don’t want these, so the command git clean will work here.

$ git clean -f

Again, we will discuss this significant point: we can’t get back these changes after performing this command.

Saving Changes on the Stash in Git

Most of the time, we are not sure about the local changes that we want anymore or not. In this case, we won’t discard them. Rather than that, we will save them temporarily using stash as mentioned below.

$ git stash --include-untracked

This will give us a clean working copy, and all the changes are saved on Git’s Stash to restore them from here if we want them later.

$ git stash pop

Here, the options pop will commit the last saved state and discard and clean it from the stash.

DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.