LinuxCommandLibrary

git-mktree

Create tree object from staged files

TLDR

Build a tree object and verify that each tree entry's hash identifies an existing object

$ git mktree
copy

Allow missing objects
$ git mktree --missing
copy

Read the NUL ([z]ero character) terminated output of the tree object (git ls-tree -z)
$ git mktree -z
copy

Allow the creation of multiple tree objects
$ git mktree --batch
copy

Sort and build a tree from stdin (non-recursive git ls-tree output format is required)
$ git < [path/to/tree.txt] mktree
copy

SYNOPSIS

git mktree [-z] [--missing] [--batch]

PARAMETERS

-z
    Use NUL (instead of newline) to terminate pathname fields in input.

--missing
    Print SHA-1 of missing blobs/trees prefixed by '?' to stdout; do not fail.

--batch
    Process multiple trees from stdin until EOF; each tree ends with a blank line.

DESCRIPTION

git mktree is a low-level Git plumbing command for constructing tree objects, which represent directory snapshots in a Git repository. It reads structured input from standard input describing the tree's contents—files, symlinks, or subtrees—and outputs the SHA-1 hash of the newly created tree object while storing it in the Git object database.

Each input line follows this exact format: <mode> SP <type> SP <object> TAB <filename>, where:
<mode> is an octal mode like 100644 (regular file), 100755 (executable), 120000 (symlink), or 040000 (subtree).
<type> is blob, tree, or rarely commit.
<object> is the 40-character SHA-1 of the referenced object.
<filename> is the entry name (no leading slash).

Entries must appear in lexicographical order by filename for the tree to be valid. This command is invoked internally by tools like git commit but useful in scripts for building custom trees. In default mode, it processes one tree. With options, it supports batch processing, NUL-delimited input, and graceful handling of missing objects.

CAVEATS

Input entries must be sorted lexicographically by filename; unsorted or duplicate names cause failure. Filenames cannot contain TAB or LF. Objects referenced (blobs/trees) must exist unless --missing used. Command writes object to database but prints only SHA-1.

INPUT FORMAT

<mode> SP <type> SP <SHA-1> TAB <name>

Examples:
100644 blob a906cb2a4ad24b79b6f4d7d6f8c4c6e4a3b2c1d README
100755 blob 2f8b... script.sh
040000 tree 99a8... subdir/

OUTPUT

Single SHA-1 per tree (hexadecimal, 40 chars) printed to stdout. Object stored in .git/objects/.

HISTORY

Introduced in Git 1.0 (2005) by Linus Torvalds as core plumbing for object creation. Evolved with batch and -z support around Git 1.7 (2010) for fast-import/export compatibility; stable since.

SEE ALSO

Copied to clipboard