Skip to content
Tutorials Center
My learning

Topics

Git Reference ยท Plumbing Commands

git mktree command

Reference for git mktree: build a tree object from ls-tree style lines on stdin, use -z and --batch, handle missing objects, and edit trees without the index.

git mktree reads lines in the format printed by git ls-tree and writes a tree object that contains exactly those entries, then prints the tree's ID. Because the input is plain text, you can take an existing tree, edit its listing with sed or grep, and feed it back in. This lets you rewrite a tree without touching the index or the working directory.

Entries must reference objects that exist (unless you pass --missing). Sorting is handled for you: Git orders the entries the way trees require, whatever order your input has.

Terminal
git ls-tree HEAD | git mktree
printf '100644 blob <sha>\tname.txt\n' | git mktree

Try it

Bash Drop a file from a tree by editing its listing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Bash Build a nested tree from scratch

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Syntax

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

Each input line has the form <mode> SP <type> SP <object> TAB <name>. This is the output format of git ls-tree without --abbrev.

Name Description
-z Lines are terminated by NUL instead of newline, and names are not quoted.
--missing Allow objects that are not in the database. By default they are rejected.
--batch Read several trees separated by blank lines and print one ID per tree.

Returns: the ID of the new tree.

Errors: a fatal error for malformed lines, for modes that do not match the object type, for names containing a slash, and for missing objects (without --missing).

Usage notes

  • Names are single path components. src/a.txt is not allowed; build the src tree first and reference it, as the second example does.
  • Modes: 100644 file, 100755 executable, 120000 symlink, 040000 tree, 160000 gitlink (submodule commit). ls-tree prints 040000 with a leading zero; mktree accepts it.
  • Quoted names: without -z, ls-tree quotes unusual names (spaces are fine, but non-ASCII or control characters are escaped). Round-trips through mktree work, but use -z on both sides to be safe.
  • Empty input creates the well-known empty tree, 4b825dc642cb6eb9a060e54bf8d69288fbee4904 in SHA-1 repositories.
  • Compare with the index route. read-tree + update-index + write-tree builds the same result but needs an index; mktree is index-free, which suits scripts that run in bare repositories.