Programster's Blog

Tutorials focusing on Linux, programming, and open-source

Tree - A Great Way To Display File Structure

If you've ever needed a neat way to display the your file structure, tree is an excellent solution. Below is an example:


sudo apt update && sudo apt install tree -y


Navigate to the folder you want to show the structure of, and just run the tree command on its own.


There are loads of fantastic options to get the output just how you want. I started to list them all, but the man page is right there and super easy to read. To read the manual, just use:

man tree

I'll just list the ones that are probably going to be most useful.

Show Hidden Files

By default, hidden files are not shown, if you want to include them add the -a option.

Alterinative Outputs: JSON, HTML, XML

If you are working programmatically, you might find JSON output super useful, especially when combined with other options like -h for showing file size. E.g.

[{"type":"directory","name": ".","contents":[

However, if you want to display a webpage, then use -H for html output. You have to add this with the relative path to use in hyperlinks, so this might be as simple as:

tree -H /

... or like

tree -H /symlink-to-files

.... which would output links in the generated webpage like:

<a href="/src">/src</a><br>
├── <a href="/src/aFile.txt">aFile.txt</a><br>
├── <a href="/src/folder1/">folder1</a><br>
│   ├── <a href="/src/folder1/aFileWithinFolder1.txt">aFileWithinFolder1.txt</a><br>
│   └── <a href="/src/folder1/anotherFileWithinFolder1.txt">anotherFileWithinFolder1.txt</a><br>
└── <a href="/src/folder2/">folder2</a><br>

XML output is achieved with -X

<?xml version="1.0" encoding="UTF-8"?>
  <directory name=".">
    <file name="aFile.txt"></file>
    <directory name="folder1">
      <file name="aFileWithinFolder1.txt"></file>
      <file name="anotherFileWithinFolder1.txt"></file>
    <directory name="folder2">

Print Filesize

Use -s if you want the size of the file in bytes, but -h if you want a human readable format that will use K, M, G for kilobytes, megabytes, and gigabytes etc.

Get Directory Sizes

The previous option was to print the size of the files. If you want to know how big the directory is (size of all files/folders within it recursively), then use the --du option.

Follow Symlinks

-l will follow symlinks if they point to directories, not files. Symlinks that result in recursion are avoided when detected.

Print Entire Filepath

-f prints the full path prefix for each file.

Only List Directories

-d - only list directories.

Stay Within the Filesystem

If you don't want tree to cross into another filesystem from a mount or a symlink, then juse use the -x option, (just like with ncdu).


Last updated: 16th August 2018
First published: 16th August 2018