Restoring and reverting files

Introduction to Git

George Boorman

Curriculum Manager, DataCamp

Making an error

Four files in a repo, of which three are added to the staging area and one is committed: report.md, mental health survey.csv, and summary statistics.csv

Introduction to Git

Reverting files

  • Restoring a repo to the state prior to the previous commit

  • git revert

    • Reinstates previous versions and makes a commit
    • Restores all files updated in the given commit
    • a845edcb, ebe93178, etc
    • HEAD, HEAD~1, etc
git revert HEAD
Introduction to Git

Reverting files

git revert HEAD

Text editor showing that the commit

  • Save: Ctrl + O, then Enter
  • Exit: Ctrl + X
Introduction to Git

Reverting files

[main 7d11f79] Revert "Adding fresh data for the survey."
 Date: Tue Jul 30 14:17:56 2024 +0000
 1 file changed, 3 deletions(-)
Introduction to Git

git revert flags

  • Avoid opening the text editor
    git revert --no-edit HEAD
    

 

  • Revert without committing (bring files into the staging area)
    git revert -n HEAD
    
Introduction to Git

Revert a single file

  • git revert works on commits, not individual files

  • To revert a single file:

    • git checkout
    • Use commit hash or HEAD syntax
git checkout HEAD~1 -- report.md
Introduction to Git

Checking the checkout

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

        modified:   report.md
Introduction to Git

Making a commit

git commit -m "Checkout previous version of report.md"
[main daa6c87] Checkout previous version of report.md
 1 file changed, 1 deletion(-)
Introduction to Git

Unstaging a file

Four files in a repo, of which three are added to the staging area: report.md, mental health survey.csv, and summary statistics.csv

Introduction to Git

Unstaging a file

Summary statistics is moved from the staging area back to the repo

Introduction to Git

Unstaging a single file

  • To unstage a single file:
git restore --staged summary_statistics.csv
  • Edit the file
git add summary_statistics.csv
git commit -m "Adding age summary statistics"
Introduction to Git

Unstaging all files

  • To unstage all files:
git restore --staged
Introduction to Git

Summary

Command Result
git revert HEAD Revert all files from a given commit
git revert HEAD --no-edit Revert without opening a text editor
git revert HEAD -n Revert without making a new commit
git checkout HEAD~1 -- report.md Revert a single file from the previous commit
git restore --staged report.md Remove a single file from the staging area
git restore --staged Remove all files from the staging area
Introduction to Git

Let's practice!

Introduction to Git

Preparing Video For Download...