If you want to revert local changes in a Git repository, you have several options depending on what exactly you want to achieve. Here are some common scenarios and the corresponding Git commands:
1. Discard Changes in a Specific File
To discard changes in a specific file, you can use the git checkout or git restore command:
git checkout -- path/to/your/file
or
git restore path/to/your/file
2. Discard All Local Changes in the Working Directory
To discard all local changes in the working directory, you can use the following command:
git checkout -- .
or
git restore .
3. Discard Changes in Staged Files
If you have staged changes that you want to unstage (but keep the changes in the working directory), you can use:
git reset
To discard both staged and unstaged changes, you can combine the above commands:
git reset
git checkout -- .
or
git restore --staged .
git restore .
4. Discard Changes in a Specific Commit
If you want to revert a specific commit, you can use the git revert command. This creates a new commit that undoes the changes introduced by the specified commit:
git revert <commit-hash>
5. Reset to a Previous Commit
If you want to reset your branch to a previous commit and discard all changes after that commit, you can use the git reset command with the --hard option:
git reset --hard <commit-hash>
Note: This will discard all local changes and staged changes. Use with caution.
6. Stash Changes
If you want to save your local changes temporarily and revert them, you can use git stash:
git stash
To apply the stashed changes back, you can use:
git stash apply
To remove the stash after applying, you can use:
git stash pop
Summary
git checkout -- <file> or git restore <file>: Discard changes in a specific file.
git checkout -- . or git restore .: Discard all local changes.
git reset: Unstage changes.
git reset --hard <commit-hash>: Reset to a previous commit and discard all changes.
git revert <commit-hash>: Create a new commit that undoes changes from a specific commit.
git stash: Save local changes temporarily.
Choose the command that best fits your needs based on the scenario you are dealing with.