How to compute the git hash-object of a directory?

Depending why you wish to do this, the following git command might be useful:

git ls-files -s somedirectory | git hash-object --stdin

This give a single hash which takes into account the filenames and contents.

It works like this. The git ls-files -s .... outputs a list of files and their hashes as text to stdout, then git hash-object generates a hash for the data it receives from stdin.

My use case for this is the following – I want to know whether the (git managed) files in a directory in one branch exactly(*) match those in another branch. The specific use is to compare the “directory hashes” decide whether I need to re-generate derived files which are cached.

By default git ls-files will list files in sub-directories too. If you don’t want that, try looking at answers to “how to git ls-file for just one directory level. There are also various other options to git ls-files, including the ability to specify a list of files to include.

(*) excluding hash-collisions

Leave a Comment