How can I diff binary files in git?

In order to diff binary files in git, I assume I need to set up a difftool.

What difftools work? How do you put the parameters in?

1

5 Answers

If you want to force git to show binary files diff as a plain text diff use --text option like so:

git diff --text
1

You can set a textconv config option for a filetype. See "Performing text diffs of binary files" in gitattributes(5). What you should use depends on the filetype.

Example 1:

Say you want to diff the contents of zip files. In that case you should put in one of the following files $XDG_CONFIG_HOME/git/config or $HOME/.gitconfig or $GIT_DIR/config .

[diff "zip"] textconv = unzip -v

Next time you ask for a diff on a zip file in a repo, it will call unzip -v on both version and diff the resulting text.

Example 2:

For pdf files you could use e.g. pdfinfo;

[diff "pdf"] textconv = pdfinfo

Example 3:

If there is no specific infomation utility for a filetype, you could e.g. use hexdump (comes with FreeBSD and OSX, also available on Linux):

[diff "bin"] textconv = hexdump -v -C
13

The answer from Roland Smith was helpful but is currently incomplete (see the comments) - there are two parts to this.

You can define a new diff commands in your repository's .git/config file or your personal global $XDG_CONFIG_HOME/git/config/.gitconfig (usually $HOME/.gitconfig) file, for example a hex diff command using hexdump:

[diff "hex"] textconv = hexdump -v -C binary = true

Next, you need to use the repository's .gitattributes file to tell git which files should be used with this special diff command:

# Binary files (no line-ending conversions), diff using hexdump
*.bin binary diff=hex

Like the .gitignore file, the .gitattributes file should be checked into your repository.

In my case I have several different file extensions which I want to treat as binary (e.g. avoid any line ending conversions if using git on Windows), and also see any differences via hexdump:

See also for another example defining a hexdump diff command for use with image files.

1

To create a binary patch, a patch that works for binaries instead of just saying "Binary files differ", use

git diff --binary file1 file2

This produces a "GIT binary patch" using only ASCII characters (unlike --text), suitable for emailing.

The above are comprehensive ways to do so.. however, if you just need to do it for a few files, the following method is what I use:

git checkout HEAD -- /path/to/file > ~/file
vimdiff ~/file /path/to/file

Here I am using vimdiff but you can use any other tool. The above can be also combined into a small script if you need to do this over and over again.

1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like