Recovering from mistakes without breaking teammates
In a lab with a practice remote, undo work with restore, reset and revert, rescue a lost commit with the reflog, and force-push your own branch safely with a lease.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: Create a practice remote and your clone
- Step 2: Undo changes you have not committed
- Step 3: Undo local commits with reset
- Step 4: Rescue the lost commit with the reflog
- Step 5: Undo a commit that is already on main
- Step 6: Rewrite your own pushed branch safely
- Troubleshooting
- Check your understanding
- Apply it (stretch)
- Review prompt
Lessons of Git Workflow
- Git's model: snapshots, commits and pointers Concept · 15 min
- Commit hygiene: staging hunks and writing useful messages Worked example · 15 min
- Branching, merging and resolving a real conflict Lab · 25 min
- Pull requests, reviews and short-lived branches Concept · 20 min
- Recovering from mistakes without breaking teammates Lab · 20 min
- Check: repository-state challenges Knowledge check · 8 questions
What you will learn
- Undo mistakes with revert, restore, reset and reflog, choosing the option that does not rewrite shared history.
01. Goal and setup
Everyone makes Git mistakes: a bad edit, a commit made too early, a bug that reaches main. The skill is choosing the undo that fixes your problem without rewriting history that other people already have. This lab gives you one rule of thumb per situation and practice with each tool:
- Not committed yet:
git restorefor files,git restore --stagedfor the staging area - Committed, but only on your machine:
git resetin--soft,--mixedor--hardmode - Lost a commit:
git reflog - Already shared:
git revert, which adds a new commit instead of changing old ones - Rewrote your own pushed branch:
git push --force-with-lease, never a plain--force
You need Git 2.40 or later and a POSIX shell (on Windows, Git Bash). The lab creates a bare repository called origin.git to play the part of GitHub, plus clones for you and a teammate, all inside one throwaway folder. Hashes, paths and dates in the illustrative output will differ on your machine.
02. Step 1: Create a practice remote and your clone
git --version
mkdir undo-lab && cd undo-lab
git init --bare -b main origin.git
git clone origin.git work
cd work
git config user.name "Lab Learner"
git config user.email [email protected]
cat > prices.py <<'EOF'
def discount(price, percent):
return price * (1 - percent / 100)
EOF
git add prices.py
git commit -m "Add discount calculation"
git push -u origin maingit version 2.45.4
Initialized empty Git repository in .../undo-lab/origin.git/
Cloning into 'work'...
warning: You appear to have cloned an empty repository.
done.
[main (root-commit) 3191c93] Add discount calculation
1 file changed, 2 insertions(+)
create mode 100644 prices.py
To .../undo-lab/origin.git
* [new branch] main -> main
branch 'main' set up to track 'origin/main'.A bare repository has no working tree, only the contents of a .git folder, which is what a server stores. The warning about cloning an empty repository is expected. push -u links your main to origin/main.
03. Step 2: Undo changes you have not committed
Make a bad edit and stage it, then back out in two moves.
cat > prices.py <<'EOF'
def discount(price, percent):
return price - percent
EOF
git add prices.py
git status --short
git restore --staged prices.py
git status --short
git restore prices.py
git statusM prices.py
M prices.py
On branch main
Your branch is up to date with 'origin/main'.
nothing to commit, working tree cleangit restore --staged copies the committed version back into the staging area only, so the edit moves from the first status column (staged) to the second (not staged) and the file on disk is untouched. Plain git restore then copies the staged version over the file in the working tree, which throws the edit away. The reflog cannot bring that edit back, because it was never committed; at most, git fsck --lost-found may find the copy that the earlier git add stored. Older guides use git checkout -- <file> and git reset <file> for these jobs; restore does the same with clearer names.
04. Step 3: Undo local commits with reset
git reset <commit> moves the current branch to another commit. Its mode decides what happens to the changes in the commits you step back over:
--soft: the branch moves; the changes stay staged--mixed(the default): the branch moves and the staging area is reset; the changes stay in your working tree, unstaged--hard: the branch, the staging area and the working tree all match the target; the changes are gone from your files
Because it moves a branch backwards, reset rewrites history. Use it only on commits that exist nowhere but your machine. Make two local commits first:
cat > prices.py <<'EOF'
def discount(price, percent):
return price * (1 - percent / 100)
def with_vat(price, rate=0.2):
return price * (1 + rate)
EOF
git commit -am "Add a VAT helper"
cat > prices.py <<'EOF'
def discount(price, percent):
return price * (1 - percent / 100)
def with_vat(price, rate=0.2):
return round(price * (1 + rate), 2)
EOF
git commit -am "Round VAT prices to whole cents"
git log --oneline[main da11b31] Add a VAT helper
1 file changed, 4 insertions(+)
[main d0608a1] Round VAT prices to whole cents
1 file changed, 1 insertion(+), 1 deletion(-)
d0608a1 (HEAD -> main) Round VAT prices to whole cents
da11b31 Add a VAT helper
3191c93 (origin/main) Add discount calculationNow undo the rounding commit three times, once with each mode, recommitting in between. HEAD~1 means the parent of the current commit.
git reset --soft HEAD~1
git status --short
git commit -m "Round VAT prices to whole cents"
git reset --mixed HEAD~1
git status --short
git commit -am "Round VAT prices to whole cents"
git reset --hard HEAD~1
git status
git log --onelineM prices.py
[main b9f5f35] Round VAT prices to whole cents
1 file changed, 1 insertion(+), 1 deletion(-)
Unstaged changes after reset:
M prices.py
M prices.py
[main 30c26c6] Round VAT prices to whole cents
1 file changed, 1 insertion(+), 1 deletion(-)
HEAD is now at da11b31 Add a VAT helper
On branch main
Your branch is ahead of 'origin/main' by 1 commit.
(use "git push" to publish your local commits)
nothing to commit, working tree clean
da11b31 (HEAD -> main) Add a VAT helper
3191c93 (origin/main) Add discount calculationAfter --soft, the change was staged and ready to recommit, which is handy for rewording or combining your latest commits. After --mixed, it was back in the working tree, ready to be staged again in smaller pieces with git add -p. After --hard, the rounding change is gone from both your files and your branch. Each recommit usually gets a new ID because its timestamp differs. Commit times count whole seconds, so if the pasted block ran within one second, the IDs can match: identical content, same ID, as in lesson 1. Run them one at a time to see distinct IDs.
05. Step 4: Rescue the lost commit with the reflog
The rounding commit is no longer on any branch, but it has not been deleted. Git keeps a reflog: a private, local diary of every position HEAD and each branch have had. By default, entries for commits that are no longer on any branch are kept for 30 days and the rest for 90, and Git does not garbage-collect a commit while a reflog entry still refers to it.
git reflog -6da11b31 (HEAD -> main) HEAD@{0}: reset: moving to HEAD~1
30c26c6 HEAD@{1}: commit: Round VAT prices to whole cents
da11b31 (HEAD -> main) HEAD@{2}: reset: moving to HEAD~1
b9f5f35 HEAD@{3}: commit: Round VAT prices to whole cents
da11b31 (HEAD -> main) HEAD@{4}: reset: moving to HEAD~1
d0608a1 HEAD@{5}: commit: Round VAT prices to whole centsRead it from the top: HEAD@{0} is where you are now and HEAD@{1} is one move earlier, which is the commit you want. You can refer to it as HEAD@{1} or by the hash on that line. Your working tree is clean, so it is safe to move the branch back with --hard. (With uncommitted work in progress you would instead create a branch at that commit with git branch rescue HEAD@{1}.) Then push the two local commits.
git reset --hard HEAD@{1}
git log --oneline
git pushHEAD is now at 30c26c6 Round VAT prices to whole cents
30c26c6 (HEAD -> main) Round VAT prices to whole cents
da11b31 Add a VAT helper
3191c93 (origin/main) Add discount calculation
To .../undo-lab/origin.git
3191c93..30c26c6 main -> main06. Step 5: Undo a commit that is already on main
Now the dangerous case: a commit with a bug reaches the shared main, another commit lands after it, and a teammate clones the repository. Simulate that:
cat > prices.py <<'EOF'
def discount(price, percent):
return price * (1 - percent / 10)
def with_vat(price, rate=0.2):
return round(price * (1 + rate), 2)
EOF
git commit -am "Simplify the discount formula"
cat >> prices.py <<'EOF'
FREE_SHIPPING_OVER = 50
EOF
git commit -am "Add a free-shipping threshold"
git push
git clone -q ../origin.git ../teammate
git log --oneline[main 520990d] Simplify the discount formula
1 file changed, 1 insertion(+), 1 deletion(-)
[main 53896cf] Add a free-shipping threshold
1 file changed, 3 insertions(+)
To .../undo-lab/origin.git
30c26c6..53896cf main -> main
53896cf (HEAD -> main, origin/main) Add a free-shipping threshold
520990d Simplify the discount formula
30c26c6 Round VAT prices to whole cents
da11b31 Add a VAT helper
3191c93 Add discount calculationpercent / 10 turns a 25 % discount into a 250 % one. Resetting main to before that commit would need a force-push, would throw away the free-shipping commit as well, and would leave your teammate's clone holding commits that main no longer has. Revert instead: Git works out the inverse of that one commit and records it as a new commit on top. The faulty commit is HEAD~1 here; in real life you would copy its hash from git log.
git revert --no-edit HEAD~1
git log --oneline -4
git push
cd ../teammate
git pull
cd ../workAuto-merging prices.py
[main 14b4ef5] Revert "Simplify the discount formula"
Date: Sat Oct 17 13:48:19 2026 +0000
1 file changed, 1 insertion(+), 1 deletion(-)
14b4ef5 (HEAD -> main) Revert "Simplify the discount formula"
53896cf (origin/main) Add a free-shipping threshold
520990d Simplify the discount formula
30c26c6 Round VAT prices to whole cents
To .../undo-lab/origin.git
53896cf..14b4ef5 main -> main
From .../undo-lab/work/../origin
53896cf..14b4ef5 main -> origin/main
Updating 53896cf..14b4ef5
Fast-forward
prices.py | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)The faulty commit is still in the history, followed by its undo, and the free-shipping commit is untouched. Your teammate's pull is an ordinary fast-forward. Without --no-edit, Git opens your editor with a default message (Revert "…" followed by This reverts commit <hash>.); add a line saying what broke. On a protected main you would make the revert on a branch and merge it through a pull request. GitHub also offers a Revert button on merged pull requests, which prepares that pull request for you.
07. Step 6: Rewrite your own pushed branch safely
Sometimes you do want to rewrite commits you have pushed, for example to fix a typo in a message or tidy commits on your own feature branch before review. The server already has the old commits, so the push needs force. Plain git push --force overwrites whatever is there, including commits a teammate pushed in the meantime. --force-with-lease overwrites only if the remote branch is still where your last fetch saw it.
git switch -c add-examples
echo '# Example: discount(80, 25) == 60.0' >> prices.py
git commit -am "Add a discount exampel"
git push -u origin add-examples
git commit --amend -m "Add a discount example"
git push
git push --force-with-leaseSwitched to a new branch 'add-examples'
[add-examples 2e42a52] Add a discount exampel
1 file changed, 1 insertion(+)
To .../undo-lab/origin.git
* [new branch] add-examples -> add-examples
branch 'add-examples' set up to track 'origin/add-examples'.
[add-examples 3866f4f] Add a discount example
Date: Sat Oct 17 13:48:19 2026 +0000
1 file changed, 1 insertion(+)
To .../undo-lab/origin.git
! [rejected] add-examples -> add-examples (non-fast-forward)
error: failed to push some refs to '.../undo-lab/origin.git'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. If you want to integrate the remote changes,
hint: use 'git pull' before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.
To .../undo-lab/origin.git
+ 2e42a52...3866f4f add-examples -> add-examples (forced update)The amend replaced the commit, so a normal push was refused: the remote would have lost 2e42a52. Do not follow the hint and pull here: integrating the remote branch would bring the old version of the commit back alongside the new one. This is your branch and you know the old commit should go, so the lease push is the right tool.
Now watch the lease protect a teammate. In the teammate's clone, add a commit to the same branch and push it, then amend again in your clone and try to force-push:
cd ../teammate
git config user.name "Team Mate"
git config user.email [email protected]
git fetch
git switch add-examples
echo '# Example: with_vat(10) == 12.0' >> prices.py
git commit -am "Add a VAT example"
git push
cd ../work
git commit --amend -m "Add a worked discount example"
git push --force-with-leaseFrom .../undo-lab/work/../origin
* [new branch] add-examples -> origin/add-examples
branch 'add-examples' set up to track 'origin/add-examples'.
Switched to a new branch 'add-examples'
[add-examples ad833d5] Add a VAT example
1 file changed, 1 insertion(+)
To .../undo-lab/work/../origin.git
3866f4f..ad833d5 add-examples -> add-examples
[add-examples 6613153] Add a worked discount example
Date: Sat Oct 17 13:48:19 2026 +0000
1 file changed, 1 insertion(+)
To .../undo-lab/origin.git
! [rejected] add-examples -> add-examples (stale info)
error: failed to push some refs to '.../undo-lab/origin.git'Stale info means the remote branch has moved since your last fetch. A plain --force would have silently deleted your teammate's commit. Fetch and look before doing anything else:
git fetch
git status -sb
git log --oneline --graph add-examples origin/add-examples -4From .../undo-lab/origin
3866f4f..ad833d5 add-examples -> origin/add-examples
## add-examples...origin/add-examples [ahead 1, behind 2]
* 6613153 (HEAD -> add-examples) Add a worked discount example
| * ad833d5 (origin/add-examples) Add a VAT example
| * 3866f4f Add a discount example
|/
* 14b4ef5 (origin/main, main) Revert "Simplify the discount formula"Your teammate built on the commit you were about to replace. Agree with them what the branch should contain, then put your work on top of theirs (for example with git rebase origin/add-examples) and push normally. The rule of thumb: force-push only branches that are yours alone, never main, and always with the lease.
When you are finished, delete the lab: cd ../.. && rm -rf undo-lab.
08. Troubleshooting
09. Check your understanding
10. Apply it (stretch)
Finish the last step of the skill's practice project on your GitHub practice repository: merge a pull request that contains a deliberate bug, then undo it on main without force-pushing.
- Use the Revert button on the merged pull request, or create a branch and revert the change yourself. A merge commit needs
git revert -m 1 <merge-commit>; if your repository squash-merges, revert the single squashed commit without-m. Merge the revert through a pull request like any other change. - Confirm that the bug is gone and that the history shows both the original change and its revert.
- Back in the lab, run
git reflog show add-examplesto see the history of one branch rather than ofHEAD. - Write yourself a one-line rule for each tool from this lab and keep it next to your terminal.
11. Review prompt
Without looking back, match each situation to a tool and say why: an unwanted edit you have not staged; a commit you made five minutes ago and have not pushed; a commit on main that broke the build after teammates pulled it; a commit you lost after a reset. Then explain what --force-with-lease protects against that --force does not.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.