LinuxCommandLibrary

git-write-tree

Create a tree object from the index

TLDR

Create a tree object from the current index

$ git write-tree
copy

Create a tree object without checking whether objects referenced by the directory exist in the object database
$ git write-tree --missing-ok
copy

Create a tree object that represents a subdirectory (used to write the tree object for a subproject in the named subdirectory)
$ git write-tree --prefix [subdirectory]/
copy

SYNOPSIS

git write-tree [--missing] [--pretty]

PARAMETERS

--missing
    Do not abort on missing objects referenced in index; emit special "missing" placeholders in output tree instead.

--pretty
    Skip writing tree object; print index contents as human-readable tree listing like git ls-tree.

DESCRIPTION

git write-tree is a fundamental Git plumbing command that generates a tree object based on the current index file, also known as the staging area. In Git's object model, a tree object represents a directory snapshot, storing entries with file modes (permissions), names, and hashes of blob (file content) or subtree objects.

The command reads the index, which lists all staged files with their paths, builds the corresponding tree hierarchy recursively, serializes it in Git's binary format, computes the SHA-1 hash, stores the object in the .git/objects database, and prints the hash to standard output.

By default, it strictly verifies that all referenced blobs and subtrees exist in the object database, failing if any are missing. This ensures data integrity. It is invoked automatically by higher-level commands like git commit (via git commit-tree), but serves as a building block for scripts creating custom trees, testing index states, or low-level object manipulation without altering the working directory or refs.

Exclusively a plumbing tool, it expects a clean, consistent index—no merge conflicts or empty index yields the empty tree hash '4b825dc642cb6eb9a060e54bf8d69288fbee4904'. Output is machine-readable by default, suitable for piping into other Git commands.

CAVEATS

Fails if index is locked, corrupt, or contains unmerged entries. Must run inside Git repository with valid index. Does not update refs or working tree.

TYPICAL OUTPUT

Success prints tree SHA-1, e.g., 99d89f6e71...f2a2b3a7d3b.
With --pretty:
100644 blob abc123...    file.txt
040000 tree def456...    subdir/

USE CASE

Combine with git commit-tree: tree=$(git write-tree) && git commit-tree -p HEAD $tree -m "msg" creates commit from index.

HISTORY

Created by Linus Torvalds for Git's inaugural release (v1.0.0, April 2005) as core plumbing for object database operations; minimal changes since, remains essential for index-to-tree conversion.

SEE ALSO

git commit-tree(1), git ls-tree(1), git mktree(1), git update-index(1), git read-tree(1)

Copied to clipboard