ChatGPT解决这个技术问题 Extra ChatGPT

View the change history of a file using Git versioning

How do I view the history of an individual file with complete details of what has changed?

git log -- [filename] shows me the commit history of a file, but how do I see the file content that changed?

The link above (posted by Chris) is no longer valid. This link is working today: git-scm.com/book/en/v2
@chris: What is the link you speak of? In some now-deleted comment?

M
Mateen Ulhaq

This lets Git generate the patches for each log entry:

git log -p -- filename

See git help log for more options — it can actually do a lot of nice things. :)

To get just the diff for a specific commit, use

git show HEAD

or specify any other revision by identifier.

To browse the changes visually:

gitk

git show HEAD shows all files, do you know how to track an individual file (as Richard was asking for)?
you use: git show -- filename, that will show the diffs for that revision, in case exists one.
--stat is also helpful. You can use it together with -p.
This is great. gitk does not behave well when specifying paths that do not exist anymore. I used git log -p -- path .
Plus gitk looks like it was built by the boogie monster. This is a great answer and is best tailored to the original question.
M
Mateen Ulhaq

For a graphical view, use gitk:

gitk [filename]

To follow the file across file renames:

gitk --follow [filename]

But I rather even have a tool that combined the above with 'git blame' allowing me to browse the source of a file as it changes in time...
Unfortunately, this doesn't follow the history of the file past renames.
I was also looking for the history of files that were previously renamed and found this thread first. The solution is to use "git log --follow <filename>" as Phil pointed out here.
The author was looking for a command line tool. While gitk comes with GIT, it's neither a command line app nor a particularly good GUI.
Was he looking for a command line tool? "right click -> show history" certainly doesn't imply it.
M
Mateen Ulhaq
git log --follow -p -- path-to-file

This will show the entire history of the file (including history beyond renames and with diffs for each change).

In other words, if the file named bar was once named foo, then git log -p bar (without the --follow option) will only show the file's history up to the point where it was renamed -- it won't show the file's history when it was known as foo. Using git log --follow -p bar will show the file's entire history, including any changes to the file when it was known as foo. The -p option ensures that diffs are included for each change.


--stat is also helpful. You can use it together with -p.
I agree this is the REAL answer. (1.) --follow ensures that you see file renames (2.) -p ensures that you see how the file gets changed (3.) it is command line only.
@NHDaly I notice that the -- was added, but I don't know why this makes it best? What is it that it does?
@Benjohn The -- option tells Git that it has reached the end of the options and that anything that follows -- should be treated as an argument. For git log this only makes any difference if you have a path name that begins with a dash. Say you wanted to know the history of a file that has the unfortunate name "--follow": git log --follow -p -- --follow
@Benjohn: Normally, the -- is useful because it can also guard against any revision names that match the filename you've entered, which can actually be scary. For example: If you had both a branch and a file named foo, git log -p foo would show the git log history up to foo, not the history for the file foo. But @DanMoulding is right that since the --follow command only takes a single filename as its argument, this is less necessary since it can't be a revision. I just learned that. Maybe you were right to leave it out of your answer then; I'm not sure.
M
Mateen Ulhaq

tig is a terminal-based viewer with color support similar to the GUI-based gitk.

Quick Install:

APT: apt-get install tig

Homebrew (OS X): $ brew install tig

Use it to view history on a single file: tig [filename]

Or browse the detailed repository history via: tig


Excellent text-based tool, great answer. I freaked out when I saw the dependencies for gitk installing on my headless server. Would upvote again A+++
You can look at specific files with tig too, i.e. tig -- path/to/specific/file
To show all changes for a file, including renames, use tig --follow filename. Thank you so much @falken for helping us discover such a wonderful TUI tool.
f
farktronix

git whatchanged -p filename is also equivalent to git log -p filename in this case.

You can also see when a specific line of code inside a file was changed with git blame filename. This will print out a short commit id, the author, timestamp, and complete line of code for every line in the file. This is very useful after you've found a bug and you want to know when it was introduced (or who's fault it was).


"New users are encouraged to use git-log instead. (...) The command is kept primarily for historical reasons;"
P
Peter Mortensen

Sourcetree users

If you use Sourcetree to visualize your repository (it's free and quite good) you can right click a file and select Log Selected

https://i.stack.imgur.com/CHvfE.png

The display (below) is much friendlier than gitk and most the other options listed. Unfortunately (at this time) there is no easy way to launch this view from the command line — Sourcetree's CLI currently just opens repositories.

https://i.stack.imgur.com/Y9ALz.png


I particularly like the option "Follow renamed files", which allows you to see if a file was renamed or moved.
but unless i'm mistaken (please let me know!), one can only compare two versions at a time in the gui? Are there any clients which have an elegant interface for diffing several different versions at once? Possibly with a zoom-out view like in Sublime Text? That would be really useful I think.
@SamLewallen If I understand correctly you want to compare three different commits? This sounds similar to a three-way merge (mine, yours, base) — usually this strategy is used for resolving merge conflicts not necessarily comparing three arbitrary commits. There are many tools that support three way merges stackoverflow.com/questions/10998728/… but the trick is feeding these tools the specific revisions gitready.com/intermediate/2009/02/27/…
You save my life. You can use gitk to find the SHA1 hash, and then open SourceTree to enter Log Selected.. based on the found SHA1.
@MarnenLaibow-Koser I cannot remember why I need the SHA at that time. Ahaha.
C
Colin D Bennett

To show what revision and author last modified each line of a file:

git blame filename

or if you want to use the powerful blame GUI:

git gui blame filename

The blame commands do not show information about deleted code. Looking at each commit through gitk or tig shows that.
P
Peter Mortensen

Summary of other answers after reading through them and playing a bit:

The usual command line command would be

git log --follow --all -p dir/file.c

But you can also use either gitk (GUI) or tig (text UI) to give much more human-readable ways of looking at it.

gitk --follow --all -p dir/file.c

tig --follow --all -p dir/file.c

Under Debian/Ubuntu, the install command for these lovely tools is as expected:

sudo apt-get install gitk tig

And I'm currently using:

alias gdf='gitk --follow --all -p'

so that I can just type gdf dir to get a focussed history of everything in subdirectory dir.


I think this is a great answer. Maybe you arent getting voted as well because you answer other ways (IMHO better) to see the changes i.e. via gitk and tig in addition to git.
Just to add to answer. Locate the path (in git space, up to which exists in repository still). Then use the command stated above "git log --follow --all -p ". There may be the case, that the filde/folder would have been removed over the history, hence locate the maximum path that exists still, and try to fetch its history. works !
--all is for all branches, the rest is explained in @Dan's answer
Oh man, after so long time looking for good solution to track file beyond renames, finally, I found it here. Works like charm! Thanks!
P
Peter Mortensen

You can use Visual Studio Code with GitLens. It's a very powerful tool.

After having installed GitLens, go to GitLens tab, select FILE HISTORY and you can browse it.

https://i.stack.imgur.com/H0j9A.png


P
Palesz

Add this alias to your .gitconfig:

[alias]
    lg = log --all --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset'\n--abbrev-commit --date=relative

And use the command like this:

> git lg
> git lg -- filename

The output will look almost exactly the same as the gitk output. Enjoy.


After I ran that lg shortcut, I said (and I quote) "Beautiful!". However, note that the "\n" after "--graph" is an error.
Also can be used git lg -p filename - it returns a beautiful diff of searched file.
l
li ki

Lately I discovered tig and found it very useful. There are some cases I'd wish it does A or B but most of the time it's rather neat.

For your case, tig <filename> might be what you're looking for.

https://jonas.github.io/tig/


j
jitendrapurohit

You can also try this which lists the commits that has changed a specific part of a file (implemented in Git 1.8.4).

The result returned would be the list of commits that modified this particular part. Command:

git log --pretty=short -u -L <upperLimit>,<lowerLimit>:<path_to_filename>

where upperLimit is the start line number and lowerLimit is the ending line number of the file.

More details are at http://techpurohit.in/list-some-useful-git-commands.


The link is broken - the domain techpurohit.comno longer exists.
@PeterMortensen Hi, the link has been replaced with the archived one.
J
Jian

I wrote git-playback for this exact purpose

pip install git-playback
git playback [filename]

This has the benefit of both displaying the results in the command line (like git log -p) while also letting you step through each commit using the arrow keys (like gitk).


G
George Anderson

Or:

gitx -- <path/to/filename>

if you're using gitx


For some reason my gitx opens up blank.
@IgorGanapolsky you have to make sure you're at the root of your git repository
P
Peter Mortensen

In the Sourcetree UI, you can find the history of a file by selecting the 'Log Selected' option in the right click context menu:

https://i.stack.imgur.com/uxBTn.png

It would show the history of all the commits.


Where does this GUI come from?
Sourcetree UI. Thanks
what is a windows?
@Emobe: What do you mean? Can you elaborate? (The screenshot does appear to be from Microsoft Windows.)
A
Adi Shavit

If you want to see the whole history of a file, including on all other branches use:

gitk --all <filename>

P
Peter Mortensen

If you're using the Git GUI (on Windows):

Under the Repository menu, you can use "Visualize master's History". Highlight a commit in the top pane and a file in the lower right and you'll see the diff for that commit in the lower left.


How does this answer the question?
Well, OP didn't specify command line, and moving from SourceSafe (which is a GUI) it seemed relevant to point out that you could do pretty much the same thing that you can do in VSS in the Git GUI on Windows.
l
li ki

With the excellent Git Extensions, you go to a point in the history where the file still existed (if it have been deleted, otherwise just go to HEAD), switch to the File tree tab, right-click on the file and choose File history.

By default, it follows the file through the renames, and the Blame tab allows to see the name at a given revision.

It has some minor gotchas, like showing fatal: Not a valid object name in the View tab when clicking on the deletion revision, but I can live with that. :-)


Worth noting that this is Windows-only.
@EvanHahn not accurate, via mono one can use GitExtension also on Linux, we use it on ubuntu and quite happy w/ it. see git-extensions-documentation.readthedocs.org/en/latest/…
A
Antonín Slejška

SmartGit:

In the menu enable to display unchanged files: View / Show unchanged files Right click the file and select 'Log' or press 'Ctrl-L'


N
Noam Manos

If you use TortoiseGit you should be able to right click on the file and do TortoiseGit --> Show Log. In the window that pops up, make sure:

'Show Whole Project' option is not checked.

'All Branches' option is checked.


TortoiseGit (and Eclipse Git as well) somehow misses revisions of the selected file, don't count on it!
@NoamManos, I haven't encountered that issue, so I cannot verify if your statement is correct.
My mistake, it only happens in Eclipse, but in TortoiseGit you can see all revisions of a file if unchecking "show all project" + checking "all branches" (in case the file was committed on another branch, before it was merged to main branch). I'll update your answer.
P
Peter Mortensen

The answer I was looking for wasn't here. It was to see changes in files that I'd staged for commit. I.e.,

git diff --cached

If you want to include local (unstaged) changes, I often run git diff origin/master to show the complete differences between your local branch and the master branch (which can be updated from remote via git fetch)
L
Lukasz Czerwinski

git diff -U <filename> give you a unified diff.

It should be colored on red and green. If it's not, run: git config color.ui auto first.


P
Peter Mortensen

If you are using Eclipse with the Git plugin, it has an excellent comparison view with history. Right click the file and select "Compare With" → "History".


That won't allow you to find a deleted file however.
Comparing two versions of a file is different to Viewing the change history of a file
o
oracleif

I'm probably about where the OP was when this started, looking for something simple that would let me use git difftool with vimdiff to review changes to files in my repo starting from a specific commit. I wasn't too happy with answers I was finding, so I threw this git incremental reporter (gitincrep) script together and it's been useful to me:

#!/usr/bin/env bash

STARTWITH="${1:-}"
shift 1

DFILES=( "$@" )

RunDiff()
{
        GIT1=$1
        GIT2=$2
        shift 2

        if [ "$(git diff $GIT1 $GIT2 "$@")" ]
        then
                git log ${GIT1}..${GIT2}
                git difftool --tool=vimdiff $GIT1 $GIT2 "$@"
        fi
}

OLDVERS=""
RUNDIFF=""

for NEWVERS in $(git log --format=format:%h  --reverse)
do
        if [ "$RUNDIFF" ]
        then
                RunDiff $OLDVERS $NEWVERS "${DFILES[@]}"
        elif [ "$OLDVERS" ]
        then
                if [ "$NEWVERS" = "${STARTWITH:=${NEWVERS}}" ]
                then
                        RUNDIFF=true
                        RunDiff $OLDVERS $NEWVERS "${DFILES[@]}"
                fi
        fi
        OLDVERS=$NEWVERS
done

Called with no args, this will start from the beginning of the repo history, otherwise it will start with whatever abbreviated commit hash you provide and proceed to the present - you can ctrl-C at any time to exit. Any args after the first will limit the difference reports to include only the files listed among those args (which I think is what the OP wanted, and I'd recommend for all but tiny projects). If you're checking changes to specific files and want to start from the beginning, you'll need to provide an empty string for arg1. If you're not a vim user, you can replace vimdiff with your favorite diff tool.

Behavior is to output the commit comments when relevant changes are found and start offering vimdiff runs for each changed file (that's git difftool behavior, but it works here).

This approach is probably pretty naive, but looking through a lot of the solutions here and at a related post, many involved installing new tools on a system where I don't have admin access, with interfaces that had their own learning curve. The above script did what I wanted without dealing with any of that. I'll look into the many excellent suggestions here when I need something more sophisticated - but I think this is directly responsive to the OP.