Git - find commit when file was created

It is easy. following command shows first commit that file was added to the repo.

git log --oneline filename | tail -1

You can say:

git log -1 --reverse --pretty=oneline filename

This should give you the first commit.

From git help:

   -<n>
       Limits the number of commits to show. Note that this is a commit
       limiting option, see below.

   --reverse
       Output the commits in reverse order. Cannot be combined with
       --walk-reflogs.

For eliminating the commit message, say:

git log -1 --format="%H" --reverse filename

If you really want to find the commit that introduced a file you must consider renames. Thus use

git log --follow --diff-filter=A -- <filepath>

--diff-filter=[(A|C|D|M|R|T|U|X|B)…​[*]]
Select only files that are Added (A), Copied (C), Deleted (D), Modified (M), Renamed (R) ...

--follow
Continue listing the history of a file beyond renames (works only for a single file).

Eventually you also must adjust the --find-renames threshold.

--find-renames[=]
If generating diffs, detect and report renames for each commit. For following files across renames while traversing history, see --follow. If n is specified, it is a threshold on the similarity index (i.e. amount of addition/deletions compared to the file’s size). For example, -M90% means Git should consider a delete/add pair to be a rename if more than 90% of the file hasn’t changed. Without a % sign, the number is to be read as a fraction, with a decimal point before it. I.e., -M5 becomes 0.5, and is thus the same as -M50%. Similarly, -M05 is the same as -M5%. To limit detection to exact renames, use -M100%. The default similarity index is 50%.

Tags:

Git