Related: GitIsHard, links, .gitconfig

Tips and tricks for git.

Find the commit a specific copy of a file is in

Let's say you have an exact copy of a file that you know was checked into git some time ago, but you don't know exactly which revision it's located in. This will tell you. file.c is the name of the file as it's checked into git, and file.c.copy is the exact copy of the file you have.

hash=`git hash-object file.c`
for rev in `git rev-list HEAD -- file.c`; do
    git ls-tree -r $rev | fgrep -q $hash && echo SUCCESS $rev

If you know a date range for the commit in question, you can add --after=DATE --before=DATE to the git rev-list command. If you know the commit range, you can put COMMIT1..COMMIT2 in place of HEAD.

Export commits that touch certain files

This is useful if you want to copy the entire history for certain files to another repository. Note that if the commits modified any other files, this won't work.

for rev in `git log --oneline FILE1 FILE2 |
            cut -f1 -d' ' | tac`; do
    let n=n+1
    git format-patch -1 --start-number=$n $rev

Then you can import the patches into another repository with git am or git apply.