A critical part of using Git is the ability to review past commits, see exactly what changed, and safely revert or undo actions you have taken. This chapter covers the main commands for history examination and local file management.
1. Reviewing Commit History (git log)
The git log command displays a chronological list of all commits in the current repository. Each entry includes the author, date, and the commit message.
Basic Execution
git log
Common Log Options
| Option | Command | Purpose |
| One-Line Summary | git log --oneline | Displays each commit on a single line (shortened hash and subject). Essential for readability. |
| Viewing Changes | git log -p | Shows the full difference (patch) introduced by each commit. |
| Limiting Output | git log -n 5 | Shows only the last 5 commits. |
| Graph View | git log --graph --oneline | Shows a visual ASCII graph of the branch history. |
2. Viewing Changes (git diff)
The git diff command is used to see the difference between two states in your repository. This is vital before staging or committing.
Common git diff Uses
| Scenario | Command | Purpose |
| Working vs. Staging | git diff | Shows unstaged changes—what you’ve modified but haven’t run git add on. |
| Staging vs. Last Commit | git diff --staged | Shows staged changes—what you’ve run git add on and what will be included in the next commit. |
| Working vs. Last Commit | git diff HEAD | Shows all modifications (staged and unstaged) since the last commit. |
3. Undoing Local Changes (Working Directory)
If you modify a file and decide you want to discard those changes, you can revert the file back to its last committed state.
Discarding Modifications
To discard all unstaged changes in a specific file and restore it to its last committed state:
git checkout -- index.html
Warning: This command is destructive and removes all changes from your Working Directory permanently. Use with caution.
4. Undoing Staged Changes (Staging Area)
If you have used git add but realize you don’t want those files in the next commit, you need to unstage them.
Unstaging Files
To remove a file from the Staging Area, moving it back to the Working Directory’s “modified” state:
git reset HEAD file.js
5. Amending the Last Commit
If you immediately notice a typo in your commit message, or forgot to include a small file in the very last commit, you can use the amend option to safely update the snapshot.
Amending Command
This command opens the commit message editor, allowing you to change the message and include anything currently in the Staging Area into the last commit.
git commit --amend
Note: Amending creates a new commit ID (hash) that replaces the old one. Never amend commits that have already been pushed to a shared remote repository.
