Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 5 of 6 · Lab · 20 min · revision 3

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

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 restore for files, git restore --staged for the staging area
  • Committed, but only on your machine: git reset in --soft, --mixed or --hard mode
  • 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

Commands
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 main
Illustrative output (your Git version, paths and commit hashes differ)
git 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.

Commands
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 status
Expected output
M  prices.py
 M prices.py
On branch main
Your branch is up to date with 'origin/main'.

nothing to commit, working tree clean

git 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:

Commands
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
Illustrative output (your commit hashes differ)
[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 calculation

Now undo the rounding commit three times, once with each mode, recommitting in between. HEAD~1 means the parent of the current commit.

Commands
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 --oneline
Illustrative output (your commit hashes differ)
M  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 calculation

After --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.

Commands
git reflog -6
Illustrative output (your commit hashes differ)
da11b31 (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 cents

Read 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.

Commands
git reset --hard HEAD@{1}
git log --oneline
git push
Illustrative output (your commit hashes differ)
HEAD 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 -> main

06. 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:

Commands
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
Illustrative output (your commit hashes differ)
[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 calculation

percent / 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.

Commands
git revert --no-edit HEAD~1
git log --oneline -4
git push
cd ../teammate
git pull
cd ../work
Illustrative output (your commit hashes and dates differ)
Auto-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.

Commands
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-lease
Illustrative output (your commit hashes and dates differ)
Switched 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:

Commands
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-lease
Illustrative output (your commit hashes and dates differ)
From .../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:

Commands
git fetch
git status -sb
git log --oneline --graph add-examples origin/add-examples -4
Illustrative output (your commit hashes differ)
From .../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

Practice check · 3 questions

Choosing the right undo

Use what you saw in the lab.

Q1. You want to split your last commit, which nobody else has, into two smaller commits. Which command removes the commit but leaves all its changes in the working tree, unstaged and ready for `git add -p`?
Q2. `git push --force-with-lease` is rejected with "stale info". What does that tell you?
Q3. Which of these can `git reflog` not help you get back?
Practice only: not graded, not saved, not evidence.

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.

  1. 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.
  2. Confirm that the bug is gone and that the history shows both the original change and its revert.
  3. Back in the lab, run git reflog show add-examples to see the history of one branch rather than of HEAD.
  4. 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.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check