Open In App

How to Discard Changes in Git?

Last Updated : 23 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In Git, "discard changes" refers to reverting modifications made to files in your working directory back to their state in the last commit, effectively disregarding any changes you've made since then. This action can be useful if you've made changes that you no longer want to keep or if you want to start over from the last committed state.

Steps to Setup Github

1. Open GitHub by typing the following URL into the browser

https://github.com/

2. Create an Account in Git Hub using your necessary credentials.

3. Open your GitHub account and click on new on the dashboard to create a new repository.

Screenshot-(199)-(1)
how to discard changes in git

4. Give your repository name and select the repository as public or private according to your requirement and click Create Repository.

5. Install gitbash or type the following commands in the terminal to push files and folders in your repository. Create a any file or folder I created index.html for demo purpose

HTML
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h2>Welcome To GFG</h2>
<p>How to discard chages in git</p>
</body>
</html>
git init
git add .
git commit -m "first commit"
git branch -M main
git remote add origin https://github.com/bishal1289/Demo.git
git push -u origin main
Screenshot-(201)
how to discard changes in git
Screenshot-(203)-(1)
how to discard changes in git

Discarding Local Changes in a File

1. Checking out the main branch

git switch main

2. Change index.html

HTML
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h2>Welcome</h2>
<p>This is the paragraph i want to revert !!!</p>
</body>
</html>


Screenshot-(248)
how to discard changes in git

3. Check the status

git status

4.Discarding the changes in the working directory

git checkout index.html
git status
cat index.html
Screenshot-(249)
how to discard changes in git

Discarding All Local Changes

1. Modifying local Files

Screenshot-(250)
how to discard changes in git

2. Discarding all Local Changes:

 git reset --hard origin/main
Screenshot-(251)
how to discard changes in git

Saving Changes on the Stash

The "git stash" command can help you to (temporarily but safely) store your uncommitted local changes - and leave you with a clean working copy.

git stash
Screenshot-(252)
how to discard changes in git

1. Continuing Where You Left Off

git stash pop
Screenshot-(253)
how to discard changes in git

Next Article
Article Tags :

Similar Reads