View git history of specific line

I want to view the commit history related to the specific line in the file. I know we can get the history of the file. Are there any commands available to sort only the commits related to one specific line?


Solution 1:

bomz gave the right option but with wrong syntax. Fixed line would look like this:

git log -L '/the line from your file/,+1:path/to/your/file.txt'

The meaning of argument to -L is "find the first occurrence of regex /the line from your file/, in path/to/your/file.txt and show the log regarding one line range starting at this point (meaning, just this line, but you could say +5 instead)".

The caveat is, if the line contains characters with special meaning in regex, you need to escape them.

However, it's likely much simpler to use line number, like this:

git log -L15,+1:'path/to/your/file.txt'

(for line 15 of file path/to/your/file.txt)

In both cases +1 can be replaced with bigger number to get more line, or with regex to match the end of selected range.

Detailed description from the docs:

-L <start>,<end>:<file>
-L :<funcname>:<file>

Trace the evolution of the line range given by "<start>,<end>" (or the function name regex <funcname>) within the <file>. You may not give any pathspec limiters. This is currently limited to a walk starting from a single revision, i.e., you may only give zero or one positive revision arguments. You can specify this option more than once.

<start> and <end> can take one of these forms:

  • number

    If <start> or <end> is a number, it specifies an absolute line number (lines count from 1).

  • /regex/

    This form will use the first line matching the given POSIX regex. If <start> is a regex, it will search from the end of the previous -L range, if any, otherwise from the start of file. If <start> is “^/regex/”, it will search from the start of file. If <end> is a regex, it will search starting at the line given by <start>.

  • +offset or -offset

    This is only valid for <end> and will specify a number of lines before or after the line given by <start>.

If “:<funcname>” is given in place of <start> and <end>, it is a regular expression that denotes the range from the first funcname line that matches <funcname>, up to the next funcname line. “:<funcname>” searches from the end of the previous -L range, if any, otherwise from the start of file. “^:<funcname>” searches from the start of file.

Solution 2:

You could use git log https://git-scm.com/docs/git-log

git log -L'the line from your file' -- path/to/your/file.txt