revert Git Command Guide
The git revert command creates new commits that undo the changes introduced by one or more existing commits. Unlike reset which rewinds history, revert preserves the complete project history by adding new commits that reverse the effects of problematic commits.
git revert Syntax:
Section titled “git revert Syntax:”git revert [--[no-]edit] [-n] [-m <parent-number>] [-s] [-S[<keyid>]] <commit>...git revert (--continue | --skip | --abort | --quit)Commit Control Options:
Section titled “Commit Control Options:”| Option | Description |
|---|---|
--edit, -e | Edit revert commit message (default) |
--no-edit | Use auto-generated commit message |
-n, --no-commit | Don’t create commit, just apply changes |
Merge Handling Options:
Section titled “Merge Handling Options:”| Option | Description |
|---|---|
-m <parent-number> | Specify parent for merge commit revert |
--mainline <parent-number> | Alternative to -m for merge commits |
Signing Options:
Section titled “Signing Options:”| Option | Description |
|---|---|
-s, --signoff | Add Signed-off-by trailer |
-S[<keyid>], --gpg-sign[=<keyid>] | GPG-sign the revert commit |
Control Options:
Section titled “Control Options:”| Option | Description |
|---|---|
--continue | Continue after resolving conflicts |
--skip | Skip current revert and continue |
--abort | Cancel revert operation |
--quit | Stop revert but keep current state |
Parameters:
Section titled “Parameters:”| Parameter | Description |
|---|---|
<commit>... | Commits to revert (one or more) |
Understanding Revert Operations:
Section titled “Understanding Revert Operations:”Revert vs Other Commands:
Section titled “Revert vs Other Commands:”Command Comparison:├── git revert: Creates new commits that undo changes (safe for shared repos)├── git reset: Rewinds branch pointer (changes history, avoid on shared branches)├── git restore: Resets individual files (doesn't affect commits)├── git rebase: Rewrites commit history (changes existing commits)└── git checkout: Switches branches/commits (can create detached HEAD)Revert Process Flow:
Section titled “Revert Process Flow:”Revert Operation:1. Identify target commit(s) to undo2. Create reverse patch for each commit3. Apply reverse changes to working tree4. Create new commit with reverse changes5. Preserve complete project history
Safety Features:├── History remains intact├── Changes are traceable├── Safe for shared repositories├── Can be reverted itself if neededSingle vs Multiple Commit Revert:
Section titled “Single vs Multiple Commit Revert:”Single Commit Revert:├── git revert <commit>├── Creates one revert commit├── Straightforward operation
Multiple Commit Revert:├── git revert <commit1> <commit2> <commit3>├── Creates multiple revert commits├── Can cause conflicts between reverts├── Consider reverting as one operationBasic Revert Examples:
Section titled “Basic Revert Examples:”Single Commit Revert:
Section titled “Single Commit Revert:”# Revert last commitgit revert HEAD
# Revert specific commitgit revert abc123
# Revert commit with custom messagegit revert -e abc123
# Revert without creating commitgit revert -n abc123Multiple Commit Revert:
Section titled “Multiple Commit Revert:”# Revert multiple commitsgit revert HEAD~2 HEAD~1 HEAD
# Revert range of commitsgit revert abc123..def456
# Revert with auto-generated messagesgit revert --no-edit abc123 def456Merge Commit Revert:
Section titled “Merge Commit Revert:”# Revert merge commit (specify parent)git revert -m 1 abc123
# Revert merge with mainline optiongit revert --mainline 1 abc123
# Check merge commit parentsgit show --pretty=raw abc123Advanced Revert Scenarios:
Section titled “Advanced Revert Scenarios:”Conflict Resolution During Revert:
Section titled “Conflict Resolution During Revert:”# Handle revert conflictsgit revert problematic-commit
# If conflicts occur:# 1. Edit conflicted files# 2. Stage resolved filesgit add resolved-file.txt
# 3. Continue revertgit revert --continue
# Or skip this revertgit revert --skip
# Or abort entire operationgit revert --abortStrategic Revert Planning:
Section titled “Strategic Revert Planning:”# Analyze commits before revertinggit log --oneline -10
# Check what changes will be revertedgit show <commit-to-revert>
# Preview revert impactgit revert --no-commit <commit>git diff --staged # See what will be revertedgit revert --abort # Cancel previewBatch Revert Operations:
Section titled “Batch Revert Operations:”# Revert multiple commits in batchcommits_to_revert=("abc123" "def456" "ghi789")
for commit in "${commits_to_revert[@]}"; do echo "Reverting $commit..." if git revert --no-edit "$commit"; then echo "✓ Successfully reverted $commit" else echo "✗ Failed to revert $commit - manual intervention needed" exit 1 fidoneConditional Revert:
Section titled “Conditional Revert:”# Revert only if tests passgit revert --no-commit problematic-commit
if run-tests.sh; then git commit -m "Revert problematic changes" echo "Revert successful"else git revert --abort echo "Revert cancelled - tests failed"fiConfiguration and Best Practices:
Section titled “Configuration and Best Practices:”Git Configuration for Revert:
Section titled “Git Configuration for Revert:”# Configure revert behaviorgit config revert.defaultHeadName "revert" # Default revert branch namegit config revert.reference true # Use revert- prefix for references
# Configure commit message editinggit config core.editor "code --wait" # Set editor for commit messagesgit config commit.verbose true # Show diff in commit message editor
# Configure GPG signinggit config commit.gpgSign true # Sign all commitsgit config user.signingKey "your-key-id" # Set signing keySafe Revert Practices:
Section titled “Safe Revert Practices:”# Always check what will be revertedgit show <commit-to-revert>
# Create backup before complex revertsgit branch backup-before-revert
# Test revert in isolationgit revert --no-commit <commit># Run tests, check functionalitygit revert --abort # If issues found
# Use descriptive commit messagesgit revert -e <commit> # Edit revert messageRevert Strategy Guidelines:
Section titled “Revert Strategy Guidelines:”# Choose revert approach based on situation:# - Single problematic commit: git revert <commit># - Multiple related commits: git revert <commit1> <commit2># - Merge commit: git revert -m 1 <merge-commit># - Batch reverts: Script with error handling# - Emergency revert: git revert --no-commit + manual testing
# General rules:# - Prefer revert over reset for shared branches# - Test reverts before pushing# - Use clear commit messages explaining why reverting# - Consider impact on collaboratorsIntegration with Development Workflows:
Section titled “Integration with Development Workflows:”Release Management Revert:
Section titled “Release Management Revert:”#!/bin/bash# Safe revert for release management
release_revert() { local bad_commit="$1" local release_branch="${2:-main}"
echo "Reverting $bad_commit from $release_branch"
# Switch to release branch git checkout "$release_branch"
# Fetch latest changes git pull origin "$release_branch"
# Create revert commit if git revert --no-edit "$bad_commit"; then echo "✓ Revert commit created"
# Run tests if run-release-tests; then # Push revert git push origin "$release_branch" echo "✓ Revert pushed to production" else echo "✗ Tests failed - revert not pushed" git reset --hard HEAD~1 fi else echo "✗ Revert failed - manual intervention needed" fi}
release_revert "bad-commit-sha" "release/v1.2"Collaborative Revert Workflow:
Section titled “Collaborative Revert Workflow:”# Collaborative revert with team coordinationcollaborative_revert() { local commit_to_revert="$1" local reason="$2"
echo "Collaborative revert of $commit_to_revert" echo "Reason: $reason"
# Notify team notify_team "Planning to revert $commit_to_revert: $reason"
# Create revert branch git checkout -b "revert-$commit_to_revert"
# Perform revert git revert --no-edit "$commit_to_revert"
# Add detailed commit message git commit --amend -m "Revert \"$commit_to_revert\"
This reverts commit $commit_to_revert.
Reason for revert: $reason
Original commit details:$(git show --no-patch --format="Author: %an <%ae>%nDate: %ad%n%n%s%n%n%b" "$commit_to_revert")"
# Create pull request # Push branch and create PR for review git push origin "revert-$commit_to_revert"
echo "Revert branch created and pushed" echo "Create pull request for team review"}
collaborative_revert "abc123" "Introduces breaking API changes"Automated Revert System:
Section titled “Automated Revert System:”# Automated revert for CI/CD failuresautomated_revert() { local failed_commit="$1" local test_command="$2"
echo "Automated revert analysis for $failed_commit"
# Test current state if $test_command; then echo "Current state is healthy - no revert needed" return 0 fi
# Test revert echo "Testing revert of $failed_commit..." if git revert --no-commit "$failed_commit" 2>/dev/null; then if $test_command; then echo "✓ Revert fixes the issue"
# Create revert commit git commit -m "Automated revert of $failed_commit
This commit was automatically reverted because it caused test failures.Original commit: $failed_commit"
echo "✓ Automated revert completed" return 0 else echo "✗ Revert doesn't fix the issue" git revert --abort fi else echo "✗ Cannot revert $failed_commit (likely merge commit or conflicts)" fi
echo "Manual intervention required" return 1}
automated_revert "HEAD" "npm test"Troubleshooting Common Issues:
Section titled “Troubleshooting Common Issues:”Revert Conflicts:
Section titled “Revert Conflicts:”# Resolve revert conflictsgit revert <problematic-commit>
# When conflicts occur:# 1. Check conflicted filesgit status
# 2. Edit conflicted files manually# Remove conflict markers (<<<<<<< ======= >>>>>>>)
# 3. Stage resolved filesgit add resolved-file.txt
# 4. Continue revertgit revert --continue
# Alternative: Abort and try different approachgit revert --abortMerge Commit Revert Issues:
Section titled “Merge Commit Revert Issues:”# Handle merge commit revertgit revert -m 1 <merge-commit>
# If wrong parent specified:git revert --abortgit revert -m 2 <merge-commit> # Try other parent
# Check merge commit structuregit show --pretty=raw <merge-commit>git log --graph --oneline -n 5Multiple Revert Conflicts:
Section titled “Multiple Revert Conflicts:”# Handle conflicts in multiple commit revertsgit revert commit1 commit2 commit3
# If conflicts in commit2:# Option 1: Resolve and continuegit add resolved-filesgit revert --continue
# Option 2: Skip problematic commitgit revert --skip # Skip commit2, continue with commit3
# Option 3: Abort all revertsgit revert --abortRevert of Revert:
Section titled “Revert of Revert:”# Undo a revert operationgit log --oneline -5 # Find revert commit
# Revert the revert commitgit revert <revert-commit-sha>
# This restores the original changesLarge Revert Operations:
Section titled “Large Revert Operations:”# Handle large reverts efficientlylarge_revert() { local commits_file="$1"
echo "Processing large revert operation..."
# Process commits in batches while read -r commit; do echo "Reverting $commit..."
if git revert --no-edit "$commit" 2>/dev/null; then echo "✓ Reverted $commit" else echo "✗ Failed to revert $commit - conflicts detected" # Handle conflicts or skip fi done < "$commits_file"}
large_revert "commits-to-revert.txt"Real-World Usage Examples:
Section titled “Real-World Usage Examples:”Bug Fix Revert:
Section titled “Bug Fix Revert:”# Revert a bug-introducing commitrevert_bug_fix() { local bug_commit="$1" local bug_description="$2"
echo "Reverting bug-introducing commit: $bug_commit" echo "Bug: $bug_description"
# Verify the commit exists and causes the bug git show "$bug_commit"
# Create revert commit git revert --edit "$bug_commit"
# In commit message editor: # "Revert bug fix for [issue] # # This reverts commit $bug_commit. # # The original fix introduced: $bug_description # Need to investigate root cause before reapplying."
echo "Revert commit created - investigate root cause before reapplying fix"}
revert_bug_fix "abc123" "causes application crashes on startup"Feature Rollback:
Section titled “Feature Rollback:”# Rollback an entire featurefeature_rollback() { local feature_commits="$1" local feature_name="$2"
echo "Rolling back feature: $feature_name"
# Get all commits for the feature commits=$(git log --oneline --grep="$feature_name" | cut -d' ' -f1)
if [ -z "$commits" ]; then echo "No commits found for feature: $feature_name" return 1 fi
echo "Found commits to revert:" echo "$commits"
# Revert commits in reverse order echo "$commits" | tac | while read -r commit; do echo "Reverting $commit..." git revert --no-edit "$commit" done
echo "Feature rollback complete" echo "Consider removing feature branch and related code"}
feature_rollback "feature/user-auth" "User Authentication"Security Patch Revert:
Section titled “Security Patch Revert:”# Revert security patches that cause issuessecurity_revert() { local security_commit="$1" local vulnerability="$2"
echo "Security revert for: $vulnerability"
# Document the revert carefully git revert --edit "$security_commit"
# Commit message should include: # - Reference to original security issue # - Why the patch is being reverted # - Alternative mitigation strategy # - Timeline for proper fix
echo "Security revert completed" echo "IMPORTANT: Implement alternative security measures immediately" echo "Schedule proper security fix deployment"}
security_revert "sec-fix-123" "CVE-2023-XXXX: Buffer overflow vulnerability"Deployment Rollback:
Section titled “Deployment Rollback:”# Rollback deployment commitsdeployment_rollback() { local deployment_tag="$1"
echo "Rolling back deployment: $deployment_tag"
# Find commits since deployment deployment_commit=$(git rev-parse "$deployment_tag") current_commit=$(git rev-parse HEAD)
if [ "$deployment_commit" = "$current_commit" ]; then echo "Already at deployment commit" return 0 fi
# Get commits to revert commits_to_revert=$(git log --oneline "$deployment_commit..HEAD" | cut -d' ' -f1)
echo "Commits to revert:" echo "$commits_to_revert"
# Revert each commit echo "$commits_to_revert" | tac | while read -r commit; do if git revert --no-edit "$commit" 2>/dev/null; then echo "✓ Reverted $commit" else echo "✗ Failed to revert $commit - manual intervention needed" exit 1 fi done
echo "Deployment rollback complete" echo "Verify system stability before next deployment"}
deployment_rollback "v1.2.0"Hotfix Management:
Section titled “Hotfix Management:”# Manage hotfix revertshotfix_revert_management() { local hotfix_commit="$1" local production_branch="${2:-main}"
echo "Hotfix revert management for $hotfix_commit"
# Check if hotfix is still needed echo "Analyzing hotfix impact..." # Run tests, check monitoring, etc.
# If hotfix causes more problems than it solves if should_revert_hotfix; then echo "Reverting hotfix..."
# Switch to production branch git checkout "$production_branch" git pull origin "$production_branch"
# Revert hotfix git revert --no-edit "$hotfix_commit"
# Test revert if run_production_tests; then git push origin "$production_branch" echo "✓ Hotfix reverted successfully" else echo "✗ Revert causes issues - manual intervention needed" git revert --abort fi else echo "Hotfix should remain in place" fi}
hotfix_revert_management "hotfix-456" "production"What’s the difference between revert and reset?
Section titled “What’s the difference between revert and reset?”revert creates new commits that undo changes (safe for shared repos); reset rewinds branch history (avoid on shared branches).
How do I revert a merge commit?
Section titled “How do I revert a merge commit?”Use git revert -m 1
Can I revert multiple commits at once?
Section titled “Can I revert multiple commits at once?”Yes, git revert
What happens if revert causes conflicts?
Section titled “What happens if revert causes conflicts?”Resolve conflicts like any merge: edit files, remove conflict markers, stage changes, then git revert —continue.
How do I undo a revert?
Section titled “How do I undo a revert?”Revert the revert commit: git revert
Can I revert without creating a commit?
Section titled “Can I revert without creating a commit?”Yes, git revert —no-commit
What’s the safest way to revert?
Section titled “What’s the safest way to revert?”Test the revert first with —no-commit, run your tests, then commit if successful. Always have a backup branch.
How do I revert a range of commits?
Section titled “How do I revert a range of commits?”Use git revert
Can revert work on public branches?
Section titled “Can revert work on public branches?”Yes, revert is designed for shared/public branches. It preserves history and is safe for collaboration.
What’s the difference between revert and cherry-pick?
Section titled “What’s the difference between revert and cherry-pick?”revert applies reverse changes from a commit; cherry-pick applies the original changes from a commit to current branch.
How do I check what a revert will do?
Section titled “How do I check what a revert will do?”Use git revert —no-commit
Can I edit the revert commit message?
Section titled “Can I edit the revert commit message?”Yes, use git revert —edit
What if I want to redo a reverted change?
Section titled “What if I want to redo a reverted change?”Revert the revert commit: git revert
How do I handle revert conflicts in automation?
Section titled “How do I handle revert conflicts in automation?”Use git revert —abort on failure, or implement conflict resolution logic in your automation scripts.
Can revert be used in CI/CD pipelines?
Section titled “Can revert be used in CI/CD pipelines?”Yes, but carefully. Use —no-commit for testing, then commit only if tests pass. Consider manual approval for production reverts.
Applications of the git revert command
Section titled “Applications of the git revert command”- Safe Change Reversal: Undo problematic commits without rewriting shared history
- Bug Fix Rollback: Remove buggy changes while preserving complete project history
- Feature Rollback: Safely remove entire features or functionality
- Security Patch Management: Revert security fixes that cause unexpected issues
- Deployment Rollback: Undo deployment commits when issues are discovered
- Collaborative Development: Safely undo changes in shared repository environments