0
0
GitHow-ToBeginner · 3 min read

How to Use git reset --hard: Syntax, Example, and Tips

Use git reset --hard <commit> to move your current branch to the specified commit and discard all changes in the working directory and staging area. This command resets your files and history to exactly match that commit, removing any uncommitted work.
📐

Syntax

The git reset --hard command has this basic syntax:

  • git reset --hard <commit>: Resets the current branch to the specified commit and discards all changes in the working directory and staging area.
  • <commit> can be a commit hash, branch name, tag, or special references like HEAD~1.
bash
git reset --hard <commit>
💻

Example

This example shows how to reset your branch to the previous commit and discard all uncommitted changes:

bash
$ git status
On branch main
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git restore <file>..." to discard changes in working directory)
	modified:   file.txt

$ git reset --hard HEAD~1
HEAD is now at 9fceb02 Fix typo in file.txt

$ git status
On branch main
nothing to commit, working tree clean
Output
HEAD is now at 9fceb02 Fix typo in file.txt On branch main nothing to commit, working tree clean
⚠️

Common Pitfalls

Be careful: git reset --hard deletes uncommitted changes permanently. You cannot recover them easily after running this command.

Common mistakes include:

  • Running it without specifying a commit, which resets to HEAD and discards all changes.
  • Using it on the wrong branch, losing work unintentionally.
  • Not pushing changes before resetting, causing loss of work on remote.

Always double-check your current branch and commit before using git reset --hard.

bash
$ git reset --hard
# This resets to HEAD and discards all changes

# Safer alternative to discard changes without resetting history:
git restore <file>
git restore .
📊

Quick Reference

CommandDescription
git reset --hard Reset branch to commit and discard all changes
git reset --hard HEADDiscard all uncommitted changes, keep current commit
git restore Discard changes in specific file without resetting history
git statusCheck current branch and changes before resetting

Key Takeaways

git reset --hard resets your branch and discards all uncommitted changes permanently.
Always confirm your current branch and commit before running git reset --hard to avoid data loss.
Use git status to review changes before resetting.
For safer discard of changes without resetting history, use git restore.
git reset --hard cannot be undone easily; use it only when sure.