使用Git查看所有本地分支中指定文件的最新提交——跨本地分支对比
Absolutely, there are Git commands that can give you exactly what you're looking for—showing all commits to a specific file across all local branches, complete with branch names, commit details, and diffs. Let's break down the solutions:
1. Show All Commits to the File Across All Branches (With Branch Names & Diffs)
This command will list every commit that modified your target file across all local branches, displaying the commit hash, branch name, timestamp, commit message, and the actual diff changes:
git log --branches --source --pretty=format:"Commit %h on branch '%(refname:short)' at %ad%n%s%n" --date=format:"%Y-%m-%d %H:%M" -p -- path/to/target/file
Let's break down what each part does:
--branches: Restricts the log to only local branches (use--allif you want to include tags/remote refs too).--source: Adds the reference (like a branch name) that led to each commit—we extract the short branch name with%(refname:short)in the format string.--pretty=format: Customizes the output to match your desired structure, showing commit hash, branch name, date, and subject.--date=format: Sets the timestamp to your preferredYYYY-MM-DD HH:MMformat.-p: Includes the patch/diff for each commit so you can see exactly what changes were made.-- path/to/target/file: Filters the log to only commits that affect this specific file.
Bonus: Track Renamed Files
If the file was renamed at any point, add --follow to track it across name changes:
git log --branches --source --follow --pretty=format:"Commit %h on branch '%(refname:short)' at %ad%n%s%n" --date=format:"%Y-%m-%d %H:%M" -p -- path/to/target/file
2. Show Only the Latest Commit Per Branch (If You Don't Need All History)
If you just want the most recent change to the file on each local branch (instead of every commit ever), use this loop:
git for-each-ref --format='%(refname:short)' refs/heads/ | while read branch; do echo -e "\n=== Branch: $branch ===" git log -1 --pretty=format:"Commit %h at %ad%n%s%n" --date=format:"%Y-%m-%d %H:%M" -p -- path/to/target/file "$branch" done
This will iterate through each local branch, show the latest commit that touched your file on that branch, and display the diff for that commit.
Why Your Previous Attempts Didn't Work
git log -p -- file: Only shows commits on your current branch (C in your example), not all branches.git log -p --all -- file: Shows commits across all branches but doesn't include branch names by default.--source: You were on the right track, but you needed to customize the--prettyformat to actually display the branch name from the source ref.
This should help you quickly identify which branch has your "practical modification" without having to check each branch manually.
内容的提问来源于stack exchange,提问作者Zeth

