When troubleshooting a bug or tracing how a piece of code evolved, you often need to answer one question: "Who changed this specific file, and when?"

While platforms like GitHub, GitLab, and Bitbucket offer a convenient "History" button in their web interfaces, running the query directly in your terminal is faster, scriptable, and much more flexible. Here is how to view the commit history for any specific file using the Git command line.

The Quick Answer: git log

The core command you are looking for is indeed git log. To inspect commits affecting a specific file, append -- followed by the file path:

git log -- path/to/your/file.ext

Tip: The double-dash (--) separates the command options/flags from the file path. While often optional, it prevents Git from getting confused if you have a branch and a file with the same name.

The Essential Flag: Handling Renamed Files (--follow)

By default, standard git log stops tracking a file if it was renamed or moved to another directory in the past. To trace the full lifecycle of a file across renames, always use the --follow flag:

git log --follow -- path/to/your/file.ext

Useful Ways to Format the Output

Depending on whether you want a quick summary or full line-by-line diffs, Git provides several formatting flags:

1. Clean, Compact List (One-Liner)

If you just want a clean list of commit hashes and commit messages, pair --follow with --oneline:

git log --oneline --follow -- path/to/your/file.ext

2. View the Exact Code Changes (Diffs)

To view the full patch (the actual lines added and deleted) for each commit affecting that file, add -p:

git log -p --follow -- path/to/your/file.ext

3. Show Summary of Changes (Stats)

If you want to see how many lines were inserted or deleted per commit without cluttering your screen with the entire diff, use --stat:

git log --stat --oneline --follow -- path/to/your/file.ext

Advanced Filtering Options

Need to narrow your search even further? You can combine your file query with standard Git log filters:

  • Filter by Author:
    git log --author="Alice" -- path/to/file.ext
  • Filter by Date:
    git log --since="2023-01-01" --until="2023-06-30" -- path/to/file.ext
  • Limit the Number of Commits:
    git log -n 5 --oneline -- path/to/file.ext

Summary Cheat Sheet

For everyday work, bookmark this command:

git log --follow --oneline -- path/to/file.ext

This gives you a concise, complete history that honors file renames—exactly what happens under the hood when you inspect file histories in web repositories.