tree (Display Directory Tree)
The tree
command is used to display directories and files in a tree structure in your command line. In the CUI environment, understanding the directory structure intuitively can be challenging. This command gives a solution for you.
Install the tree command with a package manager
The tree
command may not be preinstalled in your Linux OS. To install the command, run sudo apt install
or sudo snap install
.
sudo apt update
sudo apt install tree
Or
sudo snap install tree
Difference between ls and tree
When you run the ls
command, you can see only one layer of a specified directory. For example, when you check the root directory with the ls
command on Ubuntu OS on AWS, the result is like the one below. (Using sudo
as the directory requires the superuser permission).
sudo ls /root
snap
To understand the directory tree, you need to run the ls
command multiple times; however, if you run the tree
command, you can see the entire directory tree with one command.
sudo tree /root
/root
└── snap
├── amazon-ssm-agent
│ ├── 2012
│ ├── 7628
│ ├── common
│ └── current -> 7628
├── lxd
│ ├── 16100
│ ├── 26093
│ ├── common
│ └── current -> 26093
└── tree
└── current -> 18
-L option
As a directory may have many directories and files in it, you may not be able to display all the results. Using the less
command may be one solution but you can limit the number of layers shown by using the -L
option. For example, if you need to know only the level 2 hierarchy of the root directory, use the -L 2
option.
sudo tree /root -L 2
/root
└── snap
├── amazon-ssm-agent
├── lxd
└── tree