Module 1 · Lesson 8 of 103

Undoing and rewriting history

Undo mistakes with restore, reset, revert and stash, and rewrite history with rebase while tagging releases for reproducibility.

  • Beginner to advanced
  • 5 min read
  • 17 min lab
What you will need

Ubuntu 24.04 (WSL2, a VM, or a container) with git installed; a GitHub or GitLab account for the remotes section

Your place in the module
By the end you can 3 objectives
  • Undo work safely with git restore, git reset, git revert and git stash, and rewrite history with git rebase.
  • Recover seemingly lost commits with git reflog.
  • Tag releases with annotated tags so a shipped image can be rebuilt from the exact commit.
Video coming soonUndoing and rewriting history
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from The object store and remotes
  • git fetch downloads, git pull downloads and merges, and git push uploads.
  • The object database stores blobs, trees and commits, addressed by SHA-1 hashes under .git/objects.
  • Branches, tags and HEAD are refs that name commits, and origin/main is a local record of the remote branch, not the remote itself.
01

Undoing work: restore, reset, revert, stash

5 min read

After sharing work with a remote, the next need is fixing mistakes. This lesson answers how to undo mistakes and rewrite history without losing work.

To discard unstaged edits in one file, returning it to the staged version, use git restore:

bash
git restore main.c              # throw away working-tree edits to main.c
git restore --staged main.c     # unstage, but keep the file's edits
Discard and unstage edits with git restore
        modified:   main.c

no changes added to commit (use "git add" and/or "git commit -a")
learner@embeddex:~/lab$ # Discard it, returning main.c to HEAD
learner@embeddex:~/lab$ git restore main.c && git status
On branch main
nothing to commit, working tree clean
learner@embeddex:~/lab$ # Stage an edit, then unstage it
learner@embeddex:~/lab$ echo '// log line' >> main.c && git add main.c && git status
On branch main
Changes to be committed:
  (use "git restore --staged <file>..." to unstage)
        modified:   main.c

learner@embeddex:~/lab$ # Unstage, keeping the edit in the file
learner@embeddex:~/lab$ git restore --staged main.c && git status
On branch main
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git restore <file>..." to discard changes in working directory)
        modified:   main.c

no changes added to commit (use "git add" and/or "git commit -a")
learner@embeddex:~/lab$

To undo an entire commit, prefer git revert, which creates a new commit that applies the reverse of an earlier one. It is safe because history is only ever added to, never rewritten:

bash
git revert a1b2c3d       # a new commit that undoes commit a1b2c3d

git reset instead moves the current branch pointer backwards. Its three modes differ in how much else they touch, and this table is the one worth memorising:

git reset --soft, --mixed and --hardreset --softreset --mixedreset --hardMoves HEADyesyesyesResets the indexnoyesyesOverwritesworking filesnonoyes
reset --soft, --mixed and --hard move HEAD, and each touches one more area
bash
git reset --soft HEAD~1    # move HEAD back one; keep index and working tree
git reset --mixed HEAD~1   # move HEAD and reset the index (the default)
git reset --hard HEAD~1    # move HEAD, reset index, and overwrite working files
Rewind commits with git reset and recover with reflog
learner@embeddex:~/lab$ git reset --hard HEAD~1 && git status
HEAD is now at 6b90194 commit 1
On branch main
nothing to commit, working tree clean
learner@embeddex:~/lab$ # Only the first commit remains
learner@embeddex:~/lab$ git log --oneline
6b90194 commit 1
learner@embeddex:~/lab$ # The reflog recorded every HEAD move
learner@embeddex:~/lab$ git reflog
6b90194 HEAD@{0}: reset: moving to HEAD~1
2100d55 HEAD@{1}: reset: moving to HEAD~1
2fcec4c HEAD@{2}: reset: moving to HEAD~1
0948df9 HEAD@{3}: commit: commit 4
2fcec4c HEAD@{4}: commit: commit 3
2100d55 HEAD@{5}: commit: commit 2
6b90194 HEAD@{6}: commit (initial): commit 1
learner@embeddex:~/lab$ # Recover the lost commits via the reflog
learner@embeddex:~/lab$ git reset --hard HEAD@{3} && git log --oneline
HEAD is now at 0948df9 commit 4
0948df9 commit 4
2fcec4c commit 3
2100d55 commit 2
6b90194 commit 1
learner@embeddex:~/lab$

--hard discards uncommitted work permanently, so treat it like rm -rf: read the command twice. For work you want to set aside without committing, git stash saves uncommitted changes and returns the working tree to a clean state, and git stash pop restores them:

bash
git stash           # set aside uncommitted changes
git stash list      # see stashed changes
git stash pop       # restore the most recent stash
Going deeperThe reflog is your safety net

Every time a branch pointer or HEAD moves, Git appends a line to the reflog, a local journal of where those pointers have been. git reflog lists it, and git reset --hard HEAD@{2} can move a branch back to where it was two moves ago, recovering commits that a reset or a force-push seemed to destroy. The reflog is local and only pruned after a long time, so the rule for disasters is: do not panic, run git reflog, and restore the pointer you want.

Common mistakes and how to fix them

fatal: not a git repository means you ran a Git command outside any repository. Cause: wrong directory, or you forgot git init. Diagnose with pwd, then cd into the project or run git init.

nothing to commit after git commit. Cause: you never ran git add, so nothing is staged. Diagnose with git status, then stage with git add and commit again.

Author identity missing: Please tell me who you are. Cause: user.name and user.email are not set. Fix: set them with git config --global as shown earlier.

Your branch is ahead of origin/main. This is not an error; it means you have local commits not yet uploaded. Fix with git push when you are ready.

Merge conflict panic: you see <<<<<<< in a file and think the file is corrupted. Cause: both sides edited the same lines. Diagnose with git status, resolve the markers, git add, then git commit.

Detached HEAD after git checkout <hash>: commits you make now belong to no branch. Cause: you checked out a commit instead of a branch. Fix: git switch -c new-branch to give the state a branch, or git switch main to return.

02

Rewriting history with rebase, and tagging

4 min read

git rebase takes the commits unique to your branch and replays them onto a new base, producing a linear history instead of a merge commit:

bash
git switch feature/add-lcd
git rebase main          # replay feature commits onto the tip of main
Replay a feature branch onto main with rebase
learner@embeddex:~/lab$ # Switch to the feature branch
learner@embeddex:~/lab$ git switch feature/add-lcd
Switched to branch 'feature/add-lcd'
learner@embeddex:~/lab$ # Feature is one commit behind main
learner@embeddex:~/lab$ git log --oneline --graph --all
* f4fc32f Update main
| * 6a9196d Add lcd driver
|/
* 341a986 Add main.c
learner@embeddex:~/lab$ # Replay feature commits onto the tip of main
learner@embeddex:~/lab$ git rebase main
Successfully rebased and updated refs/heads/feature/add-lcd.
learner@embeddex:~/lab$ # History is now linear
learner@embeddex:~/lab$ git log --oneline --graph --all
* f553bc5 Add lcd driver
* f4fc32f Update main
* 341a986 Add main.c
learner@embeddex:~/lab$

Interactive rebase lets you edit history before sharing it: reorder, combine, reword or drop commits.

bash
git rebase -i HEAD~3     # edit the last three commits in an editor
How a rebase replays commitsSwitch tofeaturegit switchfeatureFind commonancestormerge baseReplaycommitsonto newbaseMove branchpointerfeature nowon mainSwitch tofeaturegit switchfeatureFind commonancestormerge baseReplaycommitsonto newbaseMove branchpointerfeature nowon main
Rebase finds the common ancestor and replays your commits onto the new base

Rebase is safe only while the commits are still private. Once you have pushed a branch and others have based work on it, rewriting its history forces them to recover, so the rule is: never rebase a shared branch. If you must update a feature branch that was pushed, force-push with git push --force-with-lease, which refuses to clobber commits that appeared on the remote since you last fetched.

Tags mark points in history that must not move, above all releases. A lightweight tag is just a fixed reference to a commit. An annotated tag (git tag -a) stores a full object with a tagger, a date and a message, and is the kind you want for anything shared:

bash
git tag v1.0.0-test               # lightweight: a name for the commit
git tag -a v1.0.0 -m "Sensor firmware 1.0.0"   # annotated: full metadata
git tag                            # list tags
git push origin v1.0.0             # push one tag
git push origin --tags             # push all tags
Tags are how firmware releases stay reproducible

A tag such as v1.4.2-rc1 should point at exactly the commit that produced a shipped image. When a customer reports a fault in firmware 1.4.2, you git switch --detach v1.4.2, rebuild with the same Yocto or Buildroot layers, and you have the code that was in the field, unchanged. Untagged "just pull the latest" releases make that reproduction impossible.

Going deeperWhy rewriting shared history is unsafe

Every commit records its parent's hash, so history is a chain of cryptographic links. Rebase and amend replace commits with new ones that have different hashes, breaking the chain for anyone who already fetched the old ones. A teammate who built on the old commits now has a fork that will not merge cleanly, and force-pushing can silently discard their work. This is why teams agree on a convention: feature branches may be rebased and force-pushed while they are yours alone, but main and any shared branch are advanced only by new commits, never rewritten.

03

Try it

1 min read

The lab turns this lesson into three working exercises. First, initialise a repository, create a branch, commit, merge it back and deliberately create and resolve a merge conflict, keeping git status, git log --graph and the reflog open as you go. Second, clone a repository you create on GitHub or GitLab, push a branch and open a merge request, then fetch and pull on a second copy to see the round trip. Third, write a .gitignore for a small project that keeps build/, *.o, .env and key files out, and confirm with git status that they no longer appear. Before starting, re-read the two deep boxes on packfiles and on refspecs, and make the reflog your reflex whenever a command feels destructive.

Key takeaways

  • git reset --hard is destructive; git revert and the reflog are the safe ways out.
  • Never rebase a branch others share, never commit secrets, and tag releases so you can reproduce an exact build.
  • git reset --soft, --mixed and --hard move HEAD and reset one more area each; --hard overwrites working files.
  • The reflog records every pointer move, so almost nothing is truly lost.
Reflect
  1. Explain to a colleague, in two sentences: undo work safely with git restore, git reset, git revert and git stash, and rewrite history with git rebase.
  2. Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
  3. What surprised you when you ran the commands yourself?
On a real board

Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.

References and further reading

Official documentation first. Links checked when the lesson was published.

Find your next step

↑ ↓ to move · Enter to open · Esc to close