Git ls-tree: Inspect Tree Objects
Inspect the contents of Git tree objects, recurse through subtrees, select paths, control output, and distinguish tree inspection from tree construction and index operations.
Advanced
A commit points to a tree
A commit records a tree object representing the committed directory snapshot. `git ls-tree` lists the entries of a tree without changing the working tree or index. A tree entry identifies a mode, object type, object ID, and pathname.
git ls-tree HEADQuick check
What does the default `git ls-tree HEAD` inspect?
Recursive versus non-recursive listing
Without `-r`, a tree is listed one level at a time: subdirectories appear as tree entries. `-r` recursively descends into subtrees and lists their entries. `-t` keeps tree entries in recursive output.
git ls-tree HEAD
git ls-tree -r HEAD
git ls-tree -r -t HEADQuick check
Which form recursively lists files while retaining directory tree entries?
Select trees or entries
Use `-d` to show only tree entries. A path argument limits the listing to matching paths. `--full-tree` makes the path interpretation start at the root even when the command is run from a subdirectory; `--full-name` keeps the paths rooted at the top-level rather than relative to the current directory.
git ls-tree -d HEAD
git ls-tree HEAD src
cd src && git ls-tree --full-name HEAD
cd src && git ls-tree --full-tree HEADControl what is printed
The command provides focused output modes. `--name-only` and `--name-status` print pathnames; `--object-only` prints object IDs. `-l` adds blob sizes. `--abbrev=<n>` controls displayed object-name length.
git ls-tree --name-only HEAD
git ls-tree --object-only HEAD
git ls-tree -l HEAD
git ls-tree --abbrev=12 HEADQuick check
Which option is appropriate when you need only the object IDs?
NUL-safe and custom output
Use `-z` when another program needs unambiguous NUL-terminated records instead of newline-separated output. `--format=<format>` exposes structured fields such as `%(objectmode)`, `%(objecttype)`, `%(objectname)`, `%(objectsize)`, and `%(path)`.
git ls-tree -z --name-only HEAD
git ls-tree --format='%(objectname)%x09%(objecttype)%x09%(path)' HEADQuick check
Why is `-z` useful when pathname data is being consumed by another program?
Do not confuse tree inspection with tree construction
`git ls-tree` reads an existing tree. `git mktree` constructs a tree object from ls-tree-formatted input. `git read-tree` instead reads tree information into the index. These commands operate at different layers and are intentionally separated in the curriculum.
Practice what you learned
Use the dedicated Git code-completion exercise for this lesson.
Thanks for your feedback.
Mark this learning resource complete to track your learning progress.