reset Git Command Guide
The git reset command resets the current branch head (HEAD) to a specified state, optionally modifying the index and working tree. It can move the branch pointer, reset staged changes, or completely reset the repository state.
git reset Syntax:
Section titled “git reset Syntax:”git reset [-q] [<tree-ish>] [--] <pathspec>...git reset [-q] [--pathspec-from-file=<file> [--pathspec-file-nul]] [<tree-ish>]git reset (--patch | -p) [<tree-ish>] [--] [<pathspec>...]git reset [--soft | --mixed [-N] | --hard | --merge | --keep] [-q] [<commit>]Reset Modes:
Section titled “Reset Modes:”| Mode | Description |
|---|---|
--soft | Reset HEAD only, keep index and working tree |
--mixed | Reset HEAD and index, keep working tree (default) |
--hard | Reset HEAD, index, and working tree |
--merge | Reset merge state, keep working tree |
--keep | Reset HEAD but keep uncommitted changes |
Path-Specific Options:
Section titled “Path-Specific Options:”| Option | Description |
|---|---|
--patch, -p | Interactively select hunks to reset |
--pathspec-from-file=<file> | Read pathspec from file |
--pathspec-file-nul | Use NUL delimiter for pathspec file |
-q, --quiet | Suppress output |
Parameters:
Section titled “Parameters:”| Parameter | Description |
|---|---|
<commit> | Target commit to reset to (default: HEAD) |
<tree-ish> | Tree object to reset index entries from |
<pathspec> | Files/directories to reset in index |
Understanding Reset Operations:
Section titled “Understanding Reset Operations:”Git’s Three Areas:
Section titled “Git’s Three Areas:”Repository Areas:├── HEAD: Current branch pointer├── Index: Staging area (next commit)└── Working Tree: Actual files
Reset Impact by Mode:├── --soft: Moves HEAD only├── --mixed: Moves HEAD + resets index└── --hard: Moves HEAD + resets index + working treeReset vs Other Commands:
Section titled “Reset vs Other Commands:”Command Comparison:├── git reset --hard: Destroys uncommitted changes├── git checkout <commit>: Switches to commit (detached HEAD)├── git revert: Creates new commit that undoes changes├── git restore: Modern way to unstage/restore files└── git reset --soft: Rewinds commits without changing filesBasic Reset Examples:
Section titled “Basic Reset Examples:”Soft Reset (Safe):
Section titled “Soft Reset (Safe):”# Undo last commit but keep changes stagedgit reset --soft HEAD~1
# Undo multiple commits softlygit reset --soft HEAD~3
# Reset to specific commit softlygit reset --soft abc123Mixed Reset (Default):
Section titled “Mixed Reset (Default):”# Unstage all changes (default behavior)git reset
# Unstage specific filegit reset HEAD file.txt
# Reset index to match HEADgit reset HEAD
# Reset to previous commit (unstages changes)git reset HEAD~1Hard Reset (Destructive):
Section titled “Hard Reset (Destructive):”# Reset everything to last commit (destroys changes)git reset --hard
# Reset to previous commit (destroys all changes)git reset --hard HEAD~1
# Reset to specific commitgit reset --hard abc123
# Force reset to remote branchgit reset --hard origin/mainAdvanced Reset Scenarios:
Section titled “Advanced Reset Scenarios:”Selective Index Reset:
Section titled “Selective Index Reset:”# Reset specific files in indexgit reset HEAD file1.txt file2.txt
# Reset directory in indexgit reset HEAD src/
# Use pathspec for complex patternsgit reset HEAD "*.tmp"Interactive Reset:
Section titled “Interactive Reset:”# Interactively unstage hunksgit reset --patch
# Interactively reset specific filesgit reset --patch HEAD file.txt
# Choose hunks to keep staged# y: stage this hunk# n: do not stage this hunk# q: quitBranch Pointer Management:
Section titled “Branch Pointer Management:”# Move branch pointer back (keep files)git reset --soft HEAD~2
# Create new branch from current stategit branch backup-branchgit reset --hard HEAD~5
# Reset to remote branchgit fetch origingit reset --hard origin/mainMerge Conflict Resolution:
Section titled “Merge Conflict Resolution:”# Abort merge and reset to pre-merge stategit reset --merge
# Keep working tree but reset merge stategit reset --merge HEAD
# Reset but keep uncommitted changesgit reset --keep HEAD~1Configuration and Best Practices:
Section titled “Configuration and Best Practices:”Git Configuration for Reset:
Section titled “Git Configuration for Reset:”# Configure reset behaviorgit config reset.quiet false # Show reset outputgit config advice.statusHints true # Show status hints
# Configure refloggit config core.logAllRefUpdates true # Enable refloggit config gc.reflogExpire 90.days # Reflog expirationSafe Reset Practices:
Section titled “Safe Reset Practices:”# Always create backup before destructive resetgit branch backup-before-reset
# Check what will be lostgit statusgit diff HEAD
# Use reflog to recovergit refloggit reset --hard HEAD@{1} # Recover from backup
# Verify reset resultgit log --oneline -5git statusReset Strategy Guidelines:
Section titled “Reset Strategy Guidelines:”# Choose reset type based on situation:# - --soft: Rewind commits, keep changes for recommit# - --mixed: Unstage changes, keep in working tree# - --hard: Complete reset, lose all changes# - --merge: Abort merge, keep working tree# - --keep: Safe rewind, preserve uncommitted changes
# General rule: Use --soft for safe rewinds, --hard only when sureIntegration with Development Workflows:
Section titled “Integration with Development Workflows:”Commit Rewriting Workflow:
Section titled “Commit Rewriting Workflow:”#!/bin/bash# Safe commit rewriting with reset
rewrite_commits() { local commits_to_rewind="$1"
echo "Rewriting last $commits_to_rewind commits..."
# Create backup git branch backup-rewrite
# Soft reset to rewind commits git reset --soft HEAD~"$commits_to_rewind"
# Make changes to combined commit # Edit files, stage changes git add . git commit -m "Combined commit message"
echo "Commits rewritten successfully" echo "Backup available in: backup-rewrite"}
rewrite_commits 3Feature Branch Cleanup:
Section titled “Feature Branch Cleanup:”# Clean up feature branch before mergecleanup_feature_branch() { local base_branch="${1:-main}"
echo "Cleaning up feature branch for merge..."
# Fetch latest base branch git fetch origin "$base_branch"
# Reset to match base branch git reset --hard "origin/$base_branch"
# Or interactively clean up commits git reset --soft "origin/$base_branch" git reset --patch HEAD # Selectively unstage
echo "Feature branch cleaned up"}
cleanup_feature_branch "develop"Emergency Recovery:
Section titled “Emergency Recovery:”# Recover from accidental resetrecover_from_reset() { echo "Attempting to recover from reset..."
# Check reflog for recovery points git reflog --oneline -10
# Recover to specific reflog entry git reset --hard HEAD@{2} # Go back 2 steps
# Or checkout specific commit git checkout abc123 # Detached HEAD state
# Create new branch from recovered state git checkout -b recovered-state
echo "Recovery attempt complete" echo "Check git log and git status"}
recover_from_resetTroubleshooting Common Issues:
Section titled “Troubleshooting Common Issues:”Accidental Hard Reset:
Section titled “Accidental Hard Reset:”# Recover from accidental hard resetrecover_hard_reset() { echo "Recovering from accidental hard reset..."
# Check reflog immediately git reflog
# Reset to before the hard reset git reset --hard HEAD@{1}
# If reflog doesn't help, check other branches git branch -a git checkout other-branch
# Last resort: Recover from remote git fetch origin git reset --hard origin/main}
recover_hard_resetReset Conflicts:
Section titled “Reset Conflicts:”# Handle reset during merge conflictshandle_reset_conflicts() { echo "Handling reset during conflicts..."
# Check current state git status
# Use appropriate reset mode if [ -n "$(git diff --cached)" ]; then # Staged changes exist git reset --merge # Reset merge state else # No staged changes git reset --keep # Safe reset fi
# Clean up untracked files if needed git clean -fd}
handle_reset_conflictsReset with Uncommitted Changes:
Section titled “Reset with Uncommitted Changes:”# Handle reset with uncommitted changessafe_reset_with_changes() { echo "Safe reset with uncommitted changes..."
# Stash changes first git stash push -m "Before reset"
# Perform reset git reset --hard HEAD~2
# Reapply changes if needed git stash pop
# Handle conflicts if they occur # Resolve conflicts manually # git add resolved-files # git commit (if needed)}
safe_reset_with_changesRemote Reset Issues:
Section titled “Remote Reset Issues:”# Handle reset with remote brancheshandle_remote_reset() { echo "Handling reset with remote branches..."
# Fetch latest remote state git fetch origin
# Check remote vs local git log --oneline HEAD..origin/main # Remote ahead git log --oneline origin/main..HEAD # Local ahead
# Reset to match remote git reset --hard origin/main
# Or rebase local changes git rebase origin/main}
handle_remote_resetReal-World Usage Examples:
Section titled “Real-World Usage Examples:”Commit Message Fix:
Section titled “Commit Message Fix:”# Fix commit message without changing contentfix_commit_message() { echo "Fixing commit message..."
# Soft reset to edit last commit git reset --soft HEAD~1
# Amend with new message git commit --amend -m "Fixed commit message"
echo "Commit message fixed"}
fix_commit_messageFeature Branch Reset:
Section titled “Feature Branch Reset:”# Reset feature branch to clean statereset_feature_branch() { local base_branch="$1"
echo "Resetting feature branch to $base_branch..."
# Fetch latest base git fetch origin "$base_branch"
# Hard reset to base (destructive!) git reset --hard "origin/$base_branch"
# Clean up any extra files git clean -fd
echo "Feature branch reset to clean state" echo "WARNING: All local changes lost!"}
reset_feature_branch "main"Interactive Commit Cleanup:
Section titled “Interactive Commit Cleanup:”# Clean up messy commit historyinteractive_cleanup() { echo "Interactive commit cleanup..."
# Create backup git branch backup-before-cleanup
# Interactive reset to clean up commits git reset --soft HEAD~5 # Rewind 5 commits
# Stage changes selectively git add -p # Interactive staging
# Create clean commit git commit -m "Clean consolidated commit"
echo "Commit history cleaned up" echo "Backup available: backup-before-cleanup"}
interactive_cleanupRepository State Reset:
Section titled “Repository State Reset:”# Complete repository state resetcomplete_reset() { local target_commit="$1"
echo "Complete repository reset to $target_commit..."
# Backup current state git tag backup-$(date +%Y%m%d-%H%M%S)
# Hard reset to target git reset --hard "$target_commit"
# Clean untracked files git clean -fd
# Reset submodules if any git submodule foreach git reset --hard
echo "Repository completely reset" echo "Backup tag created for recovery"}
complete_reset "abc123"Collaborative Reset Management:
Section titled “Collaborative Reset Management:”# Manage resets in collaborative environmentcollaborative_reset() { local target_branch="$1" local reset_type="${2:-soft}"
echo "Collaborative reset to $target_branch..."
# Check if branch is shared if git branch -r | grep -q "origin/$target_branch"; then echo "WARNING: Target branch is shared" echo "This may affect other collaborators"
# Notify team (implement notification) # send_team_notification "Resetting $target_branch"
# Use force push after reset force_push=true fi
# Perform reset case "$reset_type" in "soft") git reset --soft "$target_branch" ;; "mixed") git reset --mixed "$target_branch" ;; "hard") git reset --hard "$target_branch" ;; esac
# Push if needed if [ "$force_push" = true ]; then git push --force-with-lease origin "$target_branch" fi
echo "Collaborative reset complete"}
collaborative_reset "main" "soft"What’s the difference between reset —soft, —mixed, and —hard?
Section titled “What’s the difference between reset —soft, —mixed, and —hard?”—soft moves HEAD only (keeps changes staged); —mixed moves HEAD and unstages changes (default); —hard moves HEAD, unstages, and discards working tree changes.
How do I undo a git reset —hard?
Section titled “How do I undo a git reset —hard?”Check git reflog for the commit before reset, then git reset —hard
Can I reset specific files?
Section titled “Can I reset specific files?”Yes, git reset HEAD
What’s the difference between reset and revert?
Section titled “What’s the difference between reset and revert?”reset rewinds history (changes existing commits); revert creates new commit that undoes changes (preserves history).
How do I reset to a remote branch?
Section titled “How do I reset to a remote branch?”git fetch origin, then git reset —hard origin/branch-name. This discards local changes and matches remote exactly.
Can I reset during a merge?
Section titled “Can I reset during a merge?”Use git reset —merge to abort merge and return to pre-merge state. Use —hard only if you want to lose merge conflict resolutions.
What’s the safest way to reset?
Section titled “What’s the safest way to reset?”Create backup branch first: git branch backup, then reset. Use —soft for safety, check git status and git log after reset.
How do I reset to a specific commit?
Section titled “How do I reset to a specific commit?”git reset —hard
Can reset affect other branches?
Section titled “Can reset affect other branches?”No, reset only affects current branch. Other branches remain unchanged unless you explicitly reset them too.
What’s the difference between reset and checkout?
Section titled “What’s the difference between reset and checkout?”reset changes current branch history; checkout switches to different branch/commit (may create detached HEAD).
How do I reset the index but keep working tree?
Section titled “How do I reset the index but keep working tree?”git reset (default —mixed mode) or git reset —mixed. This unstages all changes but keeps them in working tree.
Can I reset to undo a merge?
Section titled “Can I reset to undo a merge?”git reset —hard HEAD~1 after merge undoes it completely. For safer approach, use git revert -m 1
What’s the impact of reset on collaborators?
Section titled “What’s the impact of reset on collaborators?”reset —hard on shared branches requires force push and affects collaborators. They must reset their local branches to match.
How do I reset a specific file to HEAD?
Section titled “How do I reset a specific file to HEAD?”git reset HEAD
Can I reset to undo staged changes?
Section titled “Can I reset to undo staged changes?”Yes, git reset unstages all changes, or git reset HEAD
What’s the difference between reset and restore?
Section titled “What’s the difference between reset and restore?”reset modifies branch history and index; restore is modern command for unstaging/discarding files without affecting branch history.
Applications of the git reset command
Section titled “Applications of the git reset command”- Commit History Management: Rewind commits to fix mistakes or clean up history
- Staging Area Control: Unstage files and changes before committing
- Branch State Management: Reset branches to match remote or clean states
- Merge Conflict Resolution: Abort merges and return to pre-merge state
- Repository State Cleanup: Reset to clean state for fresh development
- Collaborative Development: Synchronize local branches with remote state