patterngitTip
git blame -L: annotate specific line ranges in a file
Viewed 0 times
git blameline rangeblame -Lfunction blameannotate lines
Problem
Running
git blame on a large file produces hundreds of lines of output when you only care about who last modified a specific function or block.Solution
Use the -L flag to restrict blame to a line range or a function name:
# By line range
git blame -L 42,68 src/auth/login.js
# By function name (Git searches for the function definition)
git blame -L :handleLogin src/auth/login.js
# Follow the blame into the parent commit (like git log --follow)
git blame -L 42,68 -C -C src/auth/login.js
# Show the blamed commit's full message
git blame -L 42,68 src/auth/login.js | cut -d' ' -f1 | sort -u | xargs git show
# By line range
git blame -L 42,68 src/auth/login.js
# By function name (Git searches for the function definition)
git blame -L :handleLogin src/auth/login.js
# Follow the blame into the parent commit (like git log --follow)
git blame -L 42,68 -C -C src/auth/login.js
# Show the blamed commit's full message
git blame -L 42,68 src/auth/login.js | cut -d' ' -f1 | sort -u | xargs git show
Why
The -L flag filters the blame output to only the specified lines or function. The function form (-L :funcname) uses the same heuristics as
git diff to locate function boundaries.Gotchas
- Function name detection depends on the language's diff driver — may not work for all languages without .gitattributes configuration
- Blame shows last modification only — a line reindented in a formatting commit will show that commit, not the logic author
- Use
-wto ignore whitespace changes:git blame -w -L 42,68 file.js
Code Snippets
Targeted git blame with line range and function name
# Blame specific line range
git blame -L 100,120 src/api/users.js
# Blame a function by name
git blame -L :createUser src/api/users.js
# Ignore whitespace changes
git blame -w -L 100,120 src/api/users.js
# Follow copies and renames across files
git blame -C -C -L 100,120 src/api/users.jsContext
Investigating the history of a specific function or block of code in a large file
Revisions (0)
No revisions yet.