How to Use git blame: Syntax, Example, and Tips
Use
git blame <file> to see who last changed each line of a file along with the commit info. This helps track changes and understand code history line-by-line.Syntax
The basic syntax of git blame is simple and shows line-by-line commit info for a file.
git blame <file>: Shows the author, commit hash, and timestamp for each line in the file.-L <start,end>: Limits output to specific line numbers.--since <date>: Shows changes only after a certain date.
bash
git blame <file> git blame -L 10,20 <file> git blame --since="2 weeks ago" <file>
Example
This example shows how to use git blame on a file named app.js. It reveals who last changed each line and when.
bash
git blame app.js
Output
e5f6a3b2 (Alice 2024-06-01 10:15:30 +0000 1) const greet = () => {
3c9d7f4a (Bob 2024-06-02 14:22:10 +0000 2) console.log('Hello, world!');
3c9d7f4a (Bob 2024-06-02 14:22:10 +0000 3) }
Common Pitfalls
Common mistakes when using git blame include:
- Running it on a file not tracked by Git, which gives an error.
- Not specifying the file name, which causes a usage error.
- Misreading output by confusing commit hashes with line numbers.
Always ensure you are in a Git repository and specify the correct file path.
bash
git blame # Error: you must specify a file git blame unknownfile.js # Error: file not found or not tracked # Correct usage: git blame app.js
Quick Reference
| Option | Description |
|---|---|
<file> | File to show blame info for |
-L <start,end> | Limit output to line range |
--since=<date> | Show changes after date |
--author=<name> | Show lines changed by author |
--reverse | Show oldest changes first |
Key Takeaways
Use
git blame <file> to see who last changed each line in a file.Specify line ranges with
-L to focus on parts of a file.Always run
git blame inside a Git repository on tracked files.Read the output carefully: it shows commit hash, author, date, and line content.
Use options like
--since and --author to filter blame results.