BudiBadu Logo
Samplebadu

Git by Example: Discarding Changes

2.43.0

Learn how to permanently discard local changes to files. This example covers reverting files to their last committed state using git restore and git checkout.

Code

# 1. Modify a file
echo "Bad code" >> app.js

# 2. Discard changes in a specific file (modern way)
git restore app.js

# 3. Discard changes in a specific file (classic way)
git checkout -- app.js

# 4. Discard ALL local changes in the current directory
git restore .

# 5. Verify the file is clean
git status

# Output:
# On branch main
# nothing to commit, working tree clean

Explanation

Discarding changes is a destructive operation used when you want to throw away your local edits and revert a file back to its last committed state. This is useful when you've been experimenting with some code, realized it's a dead end, and want to start over from a clean slate. Warning: Unlike unstaging, this action cannot be undone. Once you discard these changes, they are lost forever.

Historically, the git checkout command was used for this purpose (e.g., git checkout -- file.txt). However, checkout is a complex command also used for switching branches, which often confused new users. It was easy to mix up switching branches with overwriting files.

To solve this ambiguity, Git introduced git restore. When used without the --staged flag, git restore <file> targets the working directory. It copies the file from the staging area (or HEAD if not staged) over your local file, effectively wiping out your recent changes. It is safer and more semantic.

  • Permanently deletes local modifications
  • Reverts file to the last committed version
  • git restore <file> is the modern command
  • Use with caution as data loss is permanent

Code Breakdown

5
Restores app.js from the index. This overwrites the file in your working directory with the version Git knows about, deleting your "Bad code".
8
The classic command. The double dash -- is used to tell Git that what follows is a file path, not a branch name, preventing ambiguity.
11
Restores all files in the current directory. This is a quick way to "hard reset" your working directory to the last commit.
14
Verifying the status confirms that the working tree is clean, meaning your uncommitted changes are gone.