Aller au contenu

Restoring and reverting files

Mistakes happen: a commit that contains wrong data, a file that should go back to an earlier version, or a file staged by accident. Each situation has its own command:

flowchart TD
    q{"What needs to be undone?"}
    q -- "A whole commit" --> r["git revert &lt;commit&gt;<br/>new commit that cancels it"]
    q -- "One file, back to<br/>an earlier commit" --> c["git checkout &lt;commit&gt; -- &lt;file&gt;<br/>then commit"]
    q -- "A file staged<br/>by mistake" --> s["git restore --staged &lt;file&gt;<br/>edits are kept"]

Reverting a commit: git revert

The previous pages found a bad commit in the homelab repository: 420feb7 Add media server added a line with its columns in the wrong order.

git revert restores the repository to the state it was in before a given commit, by creating a new commit that reverses that commit's changes:

  • It reinstates the previous versions of the files and makes a commit.
  • It restores all files updated in the given commit.
  • The commit to revert is given by its hash (420feb79, ...) or a HEAD reference (HEAD, HEAD~1, ...).
git revert HEAD   # undo the most recent commit

The bad commit is not deleted. The history keeps it, followed by the commit that cancels it:

%%{init: {"gitGraph": {"showBranches": false, "rotateCommitLabel": false}, "themeVariables": {"git0": "#43a047", "gitInv0": "#ffffff", "tagLabelBackground": "#e8f5e9", "tagLabelColor": "#1b5e20", "tagLabelBorder": "#2e7d32", "commitLabelFontSize": "13px"}}}%%
gitGraph TB:
    commit id: "2553c7d Create README and inventory"
    commit id: "dd032b5 Add NAS and services list"
    commit id: "cdf805a Add web server and backup reminder"
    commit id: "420feb7 Add media server (bad data)" type: REVERSE
    commit id: "4b79e23 Revert of 420feb7"

Nothing is erased: the history still shows what happened and when, which matters as soon as other people have a copy of it.

The commit message editor

By default, git revert opens a text editor with a prepared commit message:

Revert "Add media server"

This reverts commit 420feb7935469445a05b69843c384e04fed9f255.

# Please enter the commit message for your changes. Lines starting
# with '#' will be ignored, and an empty message aborts the commit.
#
# On branch main
# Changes to be committed:
#   modified:   inventory.csv
#

Keep the message as is, or explain why the commit was reverted, then save and close the editor. Git creates the commit:

[main 4b79e23] Revert "Add media server"
 1 file changed, 1 deletion(-)

Which editor opens?

Git uses the editor configured in core.editor, or the GIT_EDITOR, VISUAL, or EDITOR environment variables, with a system default as fallback, often vi (git var, GIT_EDITOR).

Editor Save Exit
nano Ctrl + O, then Enter Ctrl + X
vi / vim Esc, then :w and Enter Esc, then :q and Enter (or :wq to do both)

To always use nano for Git: git config --global core.editor nano.

git revert options

Command Effect
git revert --no-edit HEAD Reverts and commits with the default message, without opening the editor
git revert -n HEAD Reverts the changes in the files and the staging area, without making a commit (-n = --no-commit)

With -n, the reverted files are left staged: you can check them, adjust them, and then commit yourself with git commit -m "...". Options can also be written after the commit, as in git revert HEAD --no-edit.

Reverting a single file

git revert works on commits, not on individual files: it undoes every file changed by the commit. To bring back one file from an earlier commit, use git checkout with a commit reference, --, and the file name.

For example, the homelab README should go back to its very first version, before the backup reminder was added:

git checkout HEAD~4 -- README.md
Part Meaning
HEAD~4 The commit to take the file from (a hash such as 2553c7d also works)
-- Separates the commit from the file paths, so that a file name is never mistaken for a commit or branch name
README.md The file to restore

Checking the checkout

The file is restored in the working directory and staged:

$ git status
On branch main
Changes to be committed:
  (use "git restore --staged <file>..." to unstage)
    modified:   README.md

Commit it to record the restored version:

$ git commit -m "Restore README without backup reminder"
[main 1e9ae06] Restore README without backup reminder
 1 file changed, 1 deletion(-)

This overwrites your local changes

git checkout <commit> -- <file> replaces the file in the working directory without asking. Any uncommitted edits to that file are lost. Commit or copy them first.

Modern equivalent: git restore --source

Since Git 2.23, the same operation can be written with git restore, a command dedicated to restoring files:

git restore --source=HEAD~4 --staged --worktree README.md

--source selects the commit, and --staged --worktree restores both the staging area and the working directory, like the checkout form above (git restore documentation).

Unstaging files

Staging a file does not commit it: you can still take it out of the staging area.

Back in the homelab repository, a monitoring server was added to inventory.csv and services.md, and a draft notes.txt was created. Everything was staged with git add ., but notes.txt is not ready:

$ git status
On branch main
Changes to be committed:
  (use "git restore --staged <file>..." to unstage)
    modified:   inventory.csv
    new file:   notes.txt
    modified:   services.md

Unstaging a single file

git restore --staged notes.txt

The file leaves the staging area, but your edits stay in the working directory: nothing is lost. A new file goes back to being untracked:

$ git restore --staged notes.txt
$ git status
On branch main
Changes to be committed:
  (use "git restore --staged <file>..." to unstage)
    modified:   inventory.csv
    modified:   services.md

Untracked files:
  (use "git add <file>..." to include in what will be committed)
    notes.txt

You can keep editing notes.txt, then stage and commit it when it is ready. git status reminds you of the command in its hint: (use "git restore --staged <file>..." to unstage).

Unstaging all files

To unstage everything, give git restore --staged the current directory as its path:

git restore --staged .

git restore always needs at least one path. The . means every file in the current directory and below, so run it from the repository root to unstage everything. Without any path, Git stops with:

fatal: you must specify path(s) to restore

Before the first commit

In a repository with no commits yet, git status suggests git rm --cached <file>... to unstage, because there is no previous commit to restore from.

What each restore command touches

git restore --staged and git restore without --staged look alike but act on different places:

flowchart LR
    head[("Last commit<br/>HEAD")] -- "git restore --staged &lt;file&gt;<br/>unstages: edits are kept" --> idx["Staging area"]
    idx -- "git restore &lt;file&gt;<br/>discards unstaged edits" --> wd["Working directory"]
Command Effect on the staging area Effect on your file
git restore --staged <file> The staged version is replaced by the last committed one Kept: your edits stay
git restore <file> None Discarded: the file returns to its staged (or committed) version

git restore <file> permanently discards uncommitted edits. Check twice before running it.

Summary

Command Result
git revert HEAD Revert all files from a given commit, with a new commit
git revert --no-edit HEAD Revert without opening a text editor
git revert -n HEAD Revert without making a new commit
git checkout HEAD~1 -- README.md Restore a single file to its version in an earlier commit
git restore --staged README.md Remove a single file from the staging area
git restore --staged . Remove all files from the staging area

Common mistakes

  • Expecting git revert to delete a commit. It adds a new commit that cancels the old one; both stay in the history.
  • Using git revert to fix one file. It reverts every file of the commit. Use git checkout <commit> -- <file> instead.
  • Forgetting to commit after git checkout <commit> -- <file> or git revert -n. The changes are only staged until you commit.
  • Forgetting the path in git restore --staged. Use . to unstage everything.
  • Confusing git restore --staged <file> with git restore <file>. The first keeps your edits, the second discards them.

Hands-on labs

Three labs, from guided to more autonomous. Each one has its own setup, so you can do them in any order and repeat them as often as you like. Type the commands rather than pasting them, and read every output before moving on: the goal is to build reflexes, not to reach the end.

Lab 1: recover from mistakes

Objective: undo a bad commit, restore a single file from an earlier version, and fix a staging mistake.

Prerequisites and initial state: Git installed. The setup creates ~/git-practice/undo with three commits; the last one adds wrong data.

Setup:

mkdir -p ~/git-practice/undo && cd ~/git-practice/undo
git init -q -b main
git config user.name "Practice User"
git config user.email "[email protected]"
printf '# Homelab\nTODO: describe the network layout.\n' > README.md
printf 'hostname,ip,role\npi-dns,192.168.1.10,dns\n' > inventory.csv
git add . && git commit -q -m "Create README and inventory"
echo "TODO: schedule weekly backups." >> README.md
git commit -q -am "Add backup reminder"
echo "192.168.1.40,media,mediabox" >> inventory.csv
git commit -q -am "Add media server"

Tasks:

  1. The latest commit added a malformed line to inventory.csv. Undo it with a new commit, without opening an editor.
  2. The backup reminder turns out to be premature. Restore only README.md to its version in the first commit, check the status, and commit with the message Restore initial README.
  3. Create a file notes.txt, add the line nas,192.168.1.20,storage to inventory.csv, and stage both. Then unstage only notes.txt, and commit the inventory change with the message Add NAS.
  4. Stage notes.txt again, then unstage all files with a single command.

Expected result and verification:

  • git log --oneline shows, from newest to oldest: Add NAS, Restore initial README, Revert "Add media server", Add media server, Add backup reminder, Create README and inventory. The original bad commit is still there.
  • cat README.md no longer contains TODO: schedule weekly backups.
  • cat inventory.csv ends with nas,192.168.1.20,storage and does not contain 192.168.1.40,media,mediabox.
  • At the end, git status shows notes.txt as untracked and nothing staged. The file still exists.
Solution
# 1. Undo the latest commit with a new commit, no editor
git revert --no-edit HEAD
tail -1 inventory.csv                # pi-dns,192.168.1.10,dns: the bad line is gone

# 2. Restore one file from the first commit
git log --oneline                    # the first commit is now HEAD~3
git checkout HEAD~3 -- README.md     # or use the first commit's hash
git status                           # README.md under "Changes to be committed"
git commit -m "Restore initial README"

# 3. Unstage a single file
echo "draft" > notes.txt
echo "nas,192.168.1.20,storage" >> inventory.csv
git add notes.txt inventory.csv
git restore --staged notes.txt       # notes.txt is untracked again; its content is kept
git commit -m "Add NAS"

# 4. Unstage everything
git add notes.txt
git restore --staged .               # a path is required: "." means everything
git status                           # notes.txt untracked, nothing to commit
  • git revert adds Revert "Add media server" on top of the history instead of deleting the bad commit.
  • After the revert there are four commits, so the first one is HEAD~3. Counting is error-prone: copying the hash from git log --oneline is often safer.
  • git checkout <commit> -- <file> stages the restored file but does not commit it.
  • git restore --staged only changes the staging area: notes.txt keeps its content in the working directory.
  • Equivalent for task 2 with the modern syntax: git restore --source=HEAD~3 --staged --worktree README.md.

Clean up when you are done: rm -rf ~/git-practice/undo.

Lab 2: three ways to change your mind

Objective: compare three ways of undoing work on identical copies of the same repository, including undoing an undo.

Prerequisites and initial state: Git installed. The setup builds a repository with three commits, then makes three identical copies of it: try-a, try-b, and try-c. Each copy is an independent repository, so you can experiment freely.

Setup:

mkdir -p ~/git-practice/undo-3 && cd ~/git-practice/undo-3
git init -q -b main base && cd base
git config user.name "Practice User"
git config user.email "[email protected]"
printf 'hostname,ip,role\npi-dns,192.168.1.10,dns\nweb01,192.168.1.30,web\n' > inventory.csv
git add . && git commit -q -m "Create inventory"
echo "nas,192.168.1.20,storage" >> inventory.csv
git commit -q -am "Add NAS"
sed -i 's/192.168.1.10/192.168.1.11/' inventory.csv
git commit -q -am "Change DNS address"
cd ..
cp -r base try-a && cp -r base try-b && cp -r base try-c

Tasks:

  1. In try-a, undo the latest commit with a new commit, without opening an editor. Then change your mind: the new address was right after all. Undo the undo, and check the inventory.
  2. In try-b, undo the latest commit without committing. Check the status and the staged changes. Then change your mind before committing: bring the file back to its committed version, and follow the advice of git status to cancel the revert completely.
  3. In try-c, undo the commit Add NAS, which is not the latest one, without opening an editor. Does the DNS address change survive?
  4. Compare the three histories with git log --oneline.

Expected result and verification:

  • try-a: five commits, with Reapply "Change DNS address" on top. inventory.csv contains pi-dns,192.168.1.11,dns and the NAS.
  • try-b: after git revert -n, git status shows You are currently reverting commit ... and inventory.csv as staged. At the end, git status shows nothing to commit, working tree clean without the "reverting" lines, and the history still has three commits.
  • try-c: four commits, with Revert "Add NAS" on top. inventory.csv contains pi-dns,192.168.1.11,dns and no NAS.
Solution
# 1. Revert, then revert the revert
cd ~/git-practice/undo-3/try-a
git revert --no-edit HEAD         # Revert "Change DNS address"
git revert --no-edit HEAD         # Reapply "Change DNS address"
cat inventory.csv                 # 192.168.1.11 is back
git log --oneline                 # 5 commits

# 2. Revert without committing, then cancel
cd ../try-b
git revert -n HEAD
git status                        # You are currently reverting commit ...
git diff --staged                 # -...1.11 / +...1.10
git restore --staged inventory.csv
git checkout -- inventory.csv     # file back to its committed version
git status                        # still "currently reverting": the operation is not over
git revert --abort                # the command suggested by git status
git status                        # nothing to commit, working tree clean

# 3. Revert an older commit
cd ../try-c
git revert --no-edit HEAD~1       # Revert "Add NAS"
cat inventory.csv                 # 1.11 is kept, the NAS is gone

# 4. Compare
git log --oneline
cd ../try-a && git log --oneline
cd ../try-b && git log --oneline
  • A revert is an ordinary commit, so it can be reverted too. Git names the undo of an undo Reapply "...", and the history keeps the full story: the change, its undo, and its reapplication.
  • git revert -n starts a revert operation and waits for you to commit. Restoring the file is not enough to end it; git revert --abort cancels it and puts everything back as before.
  • git revert undoes the changes of one commit, whatever its position. Later commits are kept. If a later commit modified the same or adjacent lines, the revert stops on a conflict instead, a situation covered in Intermediate Git; the web01 line between the two changes avoids it here.
  • In task 2, git revert --abort alone would also have restored the file: reading git status often shows the shortest way out.

Clean up when you are done: rm -rf ~/git-practice/undo-3.

Lab 3: final lab, from scratch to history

Objective: combine everything from this part, from git init to git revert, with fewer hints.

Prerequisites and initial state: Git installed. No setup: you start from nothing in ~/git-practice/final.

Tasks:

  1. Create a repository homelab in ~/git-practice/final, with main as its first branch, and configure a name and email for this repository only.
  2. Create README.md (a title # Homelab) and inventory.csv (a header hostname,ip,role and the line pi-dns,192.168.1.10,dns). Record both in a single commit, Create homelab notes.
  3. Add the NAS (nas,192.168.1.20,storage) to the inventory and a line TODO: schedule weekly backups. to the README, as two separate commits: Add NAS and Add backup reminder.
  4. Add a line oops to the inventory and stage it. Change your mind: unstage it, then discard it from the file.
  5. Show the history on one line per commit, then show the content of the Add NAS commit.
  6. The backup reminder was premature: undo it with a new commit, without opening an editor.
  7. Prove, with a single git diff, that README.md is now identical to its version in the first commit.

Expected result and verification:

  • git log --oneline shows Revert "Add backup reminder", Add backup reminder, Add NAS, Create homelab notes.
  • cat inventory.csv shows three lines, without oops.
  • git status shows nothing to commit, working tree clean.
  • Task 7 prints nothing.
Solution
# 1. Repository and local identity
mkdir -p ~/git-practice/final && cd ~/git-practice/final
git init -b main homelab && cd homelab
git config user.name "Practice User"
git config user.email "[email protected]"

# 2. First commit
echo "# Homelab" > README.md
printf 'hostname,ip,role\npi-dns,192.168.1.10,dns\n' > inventory.csv
git add .
git commit -m "Create homelab notes"

# 3. Two separate commits
echo "nas,192.168.1.20,storage" >> inventory.csv
git add inventory.csv && git commit -m "Add NAS"
echo "TODO: schedule weekly backups." >> README.md
git add README.md && git commit -m "Add backup reminder"

# 4. Stage, unstage, discard
echo "oops" >> inventory.csv
git add inventory.csv
git restore --staged inventory.csv
git checkout -- inventory.csv
git status                            # working tree clean

# 5. Inspect
git log --oneline
git show HEAD~1                       # Add NAS (or use its hash)

# 6. Undo with a new commit
git revert --no-edit HEAD

# 7. README.md now and in the first commit (HEAD~3)
git diff HEAD~3 HEAD README.md        # no output
  • Each task maps to one page of this part: create, stage and commit, view, compare, restore and revert.
  • An empty git diff is a positive answer: there is no difference between the two versions.
  • If any step surprised you, the matching page has a lab dedicated to it.

Clean up when you are done: rm -rf ~/git-practice/final.