Recover from Git commit or branch mistakes safely

Step-by-step terminal commands to fix commit mix-ups without losing uncommitted changes. Use it right after pushing or committing to the wrong branch.

You getSituation diagnosis, safe backup command and recovery steps

Prompt

Prompt
Act as a senior software engineer helping a teammate recover from a Git mistake without losing any uncommitted work.
- Diagnose the exact Git state based on the description below.
- Provide safe, copy-pasteable terminal commands in strict sequential order.
- Flag any command that carries risk of data loss and offer a non-destructive alternative first.
- Explain in one simple sentence what each command does to the branch pointer or working directory.
Output format:
1. Situation diagnosis (2 sentences max)
2. Safe backup command (creating a temporary recovery branch)
3. Recovery steps (numbered list with code blocks and brief explanations)
4. Verification command (how to confirm everything is fixed)

Here is my Git mistake and current status:

Example output

Example for: committed directly to main instead of a feature branch before pushing

1. Situation Diagnosis

You added commits directly to your local main branch instead of creating a feature branch first. Since you have not pushed yet, you can easily point a new branch to these commits and reset your local main back to match the remote.

2. Safe Backup Command

Create a backup branch pointing to your current state so no commits can be lost:

git branch backup-work
3. Recovery Steps
  1. Move your current commit history into your new feature branch:
git checkout -b feature-login-screen

This creates and switches to a new branch that contains your recent commits.

  1. Switch back to your local main branch:
git checkout main

This changes your active working branch back to main.

  1. Reset local main to match origin/main without touching your feature branch:
git reset --hard origin/main

This rewinds local main back to the remote server commit. Your work is safe on feature-login-screen.

4. Verification Command

Run this command to verify that main matches remote and your new branch has your commits:

git log --oneline -n 3
Written by AI from this prompt. Your results will vary.

Paste your Git status, branch names, and a quick sentence describing what went wrong into ChatGPT, Claude, or Gemini. As a follow-up, ask how to set up an alias or hook to prevent the mistake next time.

Make it repeatable

Keep using this prompt without pasting it in every time.

Keep exploring

More in Coding