git-ls-tree - Linux


Overview

git-ls-tree lists the contents of a tree object. A tree object stores a snapshot of the files and directories in a Git repository at a specific point in time. It is used to display the file structure and metadata of a specific commit, branch, or tag.

Syntax

git ls-tree [-d|-t|-f|-o] <tree-ish>

Options/Flags

  • -d: Display only directories.
  • -t: Display only tree objects.
  • -f: Display files in tree objects even if they are not in the current working directory.
  • -o: Display the object ID for each file or directory.

Examples

List the files and directories in the current commit:

git ls-tree HEAD

List only the directories in the current commit:

git ls-tree -d HEAD

List the file contents of a specific commit:

git ls-tree -f e5657629e0

Display the object ID for each file in the current commit:

git ls-tree -o HEAD

Common Issues

  • Error: Cannot find the object: This error occurs when the specified tree-ish does not exist. Ensure that you have entered the correct object ID or reference.
  • Empty output: The command may not produce any output if the tree is empty or if the specified options filter out all the content.

Integration

Combine with git diff to compare file trees:

git diff --raw HEAD HEAD^ | git ls-tree -t -r

Use with git cat-file to display file contents:

git cat-file -p $(git ls-tree -o -f HEAD^ file.txt)

Related Commands

  • git cat-file: Display the contents of a Git object.
  • git diff: Compare two tree objects.
  • git rev-parse: Obtain the object ID for a tree-ish.