Sometimes you don’t need to display only a directory’s content, but also the directory hierarchy, in order to see all the files paths.

In Linux / Unix you can do that the command tree. It displays the output in a tree form, just like pstree does with the processes.
This command is very powerfull, and can be combined with a lot of options.
If you don’t have tree installed on your Linux / Unix distro, install it first:
On Debian/Ubuntu/Linux Mint: sudo apt-get install tree
On Fedora/CentOS: sudo yum install tree
On openSUSE: sudo zypper install tree
On PC-BSD/FreeBSD as root: pkg_add -r tree
How to display directory structures with tree:
Syntax: tree /path/to/dir
If you want to view the whole tree hierarchy of the current directory, use tree | less .
How to display the directory structures by levels:
Sometimes, you want tree to display files (or folders) recurively only on some specified levels, not on the entire hierarchy.
I will explain this better on a chosen directory structure:
$ tree /home/razvan/naboo/
/home/razvan/naboo/
├── anakin
├── force
│ └── yoda
└── jedi
4 directories, 0 files
Starting from naboo with level 0 , level 1 will be naboo/anakin, naboo/force and naboo/jedi ; level 2 will be in this case naboo/force/yoda ;
Level 0 is the upper directory from the structure displayed by tree:
$ tree -L 1 naboo/
naboo/
├── anakin
├── force
└── jedi
3 directories, 0 files
$ tree -L 2 naboo/
naboo/
├── anakin
├── force
│ └── yoda
└── jedi
4 directories, 0 files
How to display also the files/folders type and permissions the dir structure:
This will display all the permissions in rwx format, along with the file/dir names.
$ tree -L 2 -p naboo
naboo
├── [drwxrwxr-x] anakin
├── [drwxrwxr-x] force
│ └── [drwxrwxr-x] yoda
└── [drwxrwxr-x] jedi
4 directories, 0 files
How to display directory structures along with the sizes in human readable format:
$ tree -L 2 -sh naboo
naboo
├── [4.0K] anakin
├── [4.0K] force
│ └── [4.0K] yoda
└── [4.0K] jedi
4 directories, 0 files
How to export the displayed tree in HTML format file:
This is usefull when you want to send your tree to someone.
$ tree -H . -o file.html
$ ls file.html
file.html
How to display hierarchical only the files or folders matching (or not) a specified pathern:
I use this when I need to display only txt files or
jpgs hierarchically:
tree -P *.txt displays only the files with the .txt extention while tree -I *.txt displays all the files except the ones with the .txt extension.
$ touch a.txt b
$ tree -P *.txt
.
└── a.txt
0 directories, 1 file
$ tree -I *.txt
.
└── b
0 directories, 1 file
Other usefull tree commands:
- tree -u /path/to/file will also display the users owning the files
- tree -g /path/to/file will also display the groups owning the files
- tree -a /path/to/file will also display the hidden files/folders
- tree -d /path/to/file will display only the directories in the hierarchy