| by Arround The Web | No comments

Bash Tree Command

The bash tree command is comparable to the well-known ls command of Linux, which is used to list the files and directories. The major difference among the commands is that the files and folders are presented in a tree-like structure by the tree command. The tree command iterates through a file hierarchy and prints the files and subdirectories in a formatted list with depth indentation. With the tree command of bash, we can quickly determine the positions of the files and folders, examine their access permissions, and also fetched the hidden files or directories.

Example # 1: Installation of Tree in Bash.

The tree command is not the built-in command of bash. We have to install the tree command in bash before calling it into the bash shell. We use the sudo privileges with the apt command to install the tree module within the bash. Once the command of installation is executed, it asked the password for authentication and then installed the tree in the bash. Here, we have already installed the tree command with the latest version.

$ Sudo apt install tree

[sudo] password for linux:
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following NEW packages will be installed:
tree
0 upgraded, 1 newly installed, 0 to remove and 0 not upgraded.
Need to get 43.0 kB of archives.
After this operation, 115 kB of additional disk space will be used.
Get:1 http://pk.archive.ubuntu.com/ubuntu focal/universe amd64 tree amd64 1.8.0-1 [43.0 kB]
Fetched 43.0 kB in 1s (33.4 kB/s)
Selecting previously unselected package tree.
(Reading database ... 188740 files and directories currently installed.)
Preparing to unpack .../tree_1.8.0-1_amd64.deb ...
Unpacking tree (1.8.0-1) ...
Setting up tree (1.8.0-1) ...
Processing triggers for man-db (2.9.1-1) ...

Now, the tree command can be used within the bash as we have installed it in our system. The following command is used to check the version of the tree command. The command returned the newest version of the tree installed in our system.

$ tree –version

tree v1.8.0 (c) 1996 - 2018 by Steve Baker, Thomas Moore, Francesc Rocher, Florian Sesser, Kyosuke Tokoro

To get any help regarding the tree command of bash, we can run the following tree command with the “–help” option. It lists out all the necessary information related to the tree command in the bash shell as shown in the image.

$ treehelp

usage: tree [-acdfghilnpqrstuvxACDFJQNSUX] [-H baseHREF] [-T title ]
[-L level [-R]] [-P pattern] [-I pattern] [-o filename] [--version]
[--help] [--inodes] [--device] [--noreport] [--nolinks] [--dirsfirst]
[--charset charset] [--filelimit[=]#] [--si] [--timefmt[=]<f>]
[--sort[=]<name>] [--matchdirs] [--ignore-case] [--fromfile] [--]
[<directory list>]
------- Listing options -------
-a            All files are listed.
-d            List directories only.
-l            Follow symbolic links like directories.
-f            Print the full path prefix for each file.
-x            Stay on current filesystem only.
-L level      Descend only level directories deep.
-R            Rerun tree when max dir level reached.
-P pattern    List only those files that match the pattern given.
-I pattern    Do not list files that match the given pattern.
--ignore-case Ignore case when pattern matching.
--matchdirs   Include directory names in -P pattern matching.
--noreport    Turn off file/directory count at end of tree listing.
--charset X   Use charset X for terminal/HTML and indentation line output.
--filelimit # Do not descend dirs with more than # files in them.
--timefmt <f> Print and format time according to the format <f>.
-o filename   Output to file instead of stdout.
------- File options -------
-q            Print non-printable characters as '?'.
-N            Print non-printable characters as is.
-Q            Quote filenames with double quotes.
-p            Print the protections for each file.
-u            Displays file owner or UID number.
-g            Displays file group owner or GID number.
-s            Print the size in bytes of each file.
-h            Print the size in a more human readable way.
--si          Like -h, but use in SI units (powers of 1000).
-D            Print the date of last modification or (-c) status change.
-F            Appends '/', '=', '*', '@', '|' or '>' as per ls -F.
--inodes      Print inode number of each file.
--device      Print device ID number to which each file belongs.
------- Sorting options -------
-v            Sort files alphanumerically by version.
-t            Sort files by last modification time.
-c            Sort files by last status change time.
-U            Leave files unsorted.
-r            Reverse the order of the sort.
--dirsfirst   List directories before files (-U disables).
--sort X      Select sort: name,version,size,mtime,ctime.
------- Graphics options -------
-i            Don't print indentation lines.
-A            Print ANSI lines graphic indentation lines.
-S            Print with CP437 (console) graphics indentation lines.
-n            Turn colorization off always (-C overrides).
-C            Turn colorization on always.
------- XML/HTML/JSON options -------
-X            Prints out an XML representation of the tree.
-J            Prints out an JSON representation of the tree.
-H baseHREF   Prints out HTML format with baseHREF as top directory.
-T string     Replace the default HTML title and H1 header with string.
--nolinks     Turn off hyperlinks in HTML output.
------- Input options -------
--fromfile    Reads paths from files (.=stdin)
------- Miscellaneous options -------
--version     Print version and exit.
--help        Print usage and this help message and exit.
--            Options processing terminator.

Further, we can also get the information of the tree command in detail by running the tree command with the “man” keyword.

$ tree man

Example # 2: Using the Tree Command in Bash.

The installation process of the tree command is accomplished in the section above. Now, to use the tree command in the bash, we just have to provide the keyword “tree” in the bash shell. The “tree” command displays the content of the specified directory in a tree format.  Here, we have given a tree command without any argument. When the tree command is executed without any argument, it displayed the tree structure of all the files and directories of the current path. The image is showing the files of our home path and the directories with their files in a tree structure. In the end, it displayed the total directories and files inside our home directory.

$ tree

├── linux1.pdf
├── linux2.pdf
└── linux3.pdf

0 directories, 3 files

The output can be made more readable by using the tree command with the “less” keyword. It comes in handy when you want to list all of the files and folders in a directory. We have given a tree command below where we use the slash “/” symbol with the tree keyword to look at the files and folders within the current directory. Then, we used the pipeline “|” symbol where the keyword “less” is specified. We can see inside the image that only a few folders and files are listed in the form of a tree-like structure. The colon “:” is located at the end which on press will show further folders and files of the current directory.

$ tree / | less

/
├── bin -> usr/bin
├── boot
│   ├── config-5.15.0-46-generic
│   ├── config-5.15.0-56-generic
│   ├── efi [error opening dir]
│   ├── grub
│   │   ├── fonts
│   │   │   └── unicode.pf2
│   │   ├── gfxblacklist.txt
│   │   ├── grub.cfg
│   │   ├── grubenv
│   │   ├── i386-pc
│   │   │   ├── 915resolution.mod
│   │   │   ├── acpi.mod
│   │   │   ├── adler32.mod
│   │   │   ├── affs.mod
│   │   │   ├── afs.mod
│   │   │   ├── ahci.mod
│   │   │   ├── all_video.mod
│   │   │   ├── aout.mod
│   │   │   ├── archelp.mod
│   │   │   ├── ata.mod
:

The bash tree command can also be used to display the process tree. Consider the command below where the “proc” represent the process running in the current directory. When we press enter to the tree command, it generates the tree process of our directory in the bash shell.

$ tree /proc

│   ├── user

│   │   ├── max_cgroup_namespaces

│   │   ├── max_fanotify_groups

│   │   ├── max_fanotify_marks

│   │   ├── max_inotify_instances

│   │   ├── max_inotify_watches

│   │   ├── max_ipc_namespaces

│   │   ├── max_mnt_namespaces

│   │   ├── max_net_namespaces

│   │   ├── max_pid_namespaces

│   │   ├── max_time_namespaces

│   │   ├── max_user_namespaces

│   │   └── max_uts_namespaces

│   └── vm

│       ├── admin_reserve_kbytes

│       ├── compaction_proactiveness

│       ├── compact_memory

│       ├── compact_unevictable_allowed

│       ├── dirty_background_bytes

│       ├── dirty_background_ratio

│       ├── dirty_bytes

│       ├── dirty_expire_centisecs

│       ├── dirty_ratio

│       ├── dirtytime_expire_seconds

│       ├── dirty_writeback_centisecs

│       ├── drop_caches

│       ├── extfrag_threshold

│       ├── hugetlb_shm_group

│       ├── laptop_mode

│       ├── legacy_va_layout

│       ├── lowmem_reserve_ratio

│       ├── max_map_count

│       ├── memory_failure_early_kill

│       ├── memory_failure_recovery

│       ├── min_free_kbytes

│       ├── min_slab_ratio

│       ├── min_unmapped_ratio

│       ├── mmap_min_addr

│       ├── mmap_rnd_bits

│       ├── mmap_rnd_compat_bits

│       ├── nr_hugepages

│       ├── nr_hugepages_mempolicy

│       ├── nr_overcommit_hugepages

│       ├── numa_stat

│       ├── numa_zonelist_order

│       ├── oom_dump_tasks

│       ├── oom_kill_allocating_task

│       ├── overcommit_kbytes

│       ├── overcommit_memory

│       ├── overcommit_ratio

│       ├── page-cluster

│       ├── page_lock_unfairness

│       ├── panic_on_oom

│       ├── percpu_pagelist_high_fraction

│       ├── stat_interval

│       ├── stat_refresh

│       ├── swappiness

│       ├── unprivileged_userfaultfd

│       ├── user_reserve_kbytes

│       ├── vfs_cache_pressure

│       ├── watermark_boost_factor

│       ├── watermark_scale_factor

│       └── zone_reclaim_mode

├── sysrq-trigger

├── sysvipc

│   ├── msg

│   ├── sem

│   └── shm

├── thread-self -> 5259/task/5259

├── timer_list

├── tty

│   ├── driver [error opening dir]

│   ├── drivers

│   ├── ldisc

│   └── ldiscs

├── uptime

├── version

├── version_signature

├── vmallocinfo

├── vmstat

└── zoneinfo

10618 directories, 169916 files

Example # 3: Using Tree Command with Different Options in Bash.

tree command option “-a”:

The tree command supports various options in bash which we have used in this section to demonstrate the performance of each tree command option in bash. Firstly, we have deployed the tree command with the option “-a”. The option “-a” fetched all the files of the directory including the hidden files which can be seen in the image of the bash shell.

tree -a

-shutdown.jsonlz4

│       │   ├── session-state.json

│       │   └── state.json

│       ├── directoryTree.json

│       ├── encrypted-openpgp-passphrase.txt

│       ├── extension-preferences.json

│       ├── extensions.json

│       ├── favicons.sqlite

│       ├── formhistory.sqlite

│       ├── global-messages-db.sqlite

│       ├── history.sqlite

│       ├── key4.db

│       ├── lock -> 127.0.1.1:+2021

│       ├── mailViews.dat

│       ├── minidumps

│       ├── openpgp.sqlite

│       ├── .parentlock

│       ├── permissions.sqlite

│       ├── pkcs11.txt

│       ├── places.sqlite

│       ├── prefs.js

│       ├── saved-telemetry-pings

│       │   └── 0c85ad5f-60c2-40d9-a342-f533e121a844

│       ├── search.json.mozlz4

│       ├── security_state

│       ├── sessionCheckpoints.json

│       ├── settings

│       │   └── data.safe.bin

│       ├── SiteSecurityServiceState.txt

│       ├── storage

│       │   ├── default

│       │   ├── ls-archive.sqlite

│       │   ├── permanent

│       │   │   └── chrome

│       │   │       ├── idb

│       │   │       │   ├── 3870112724rsegmnoittet-es.files

│       │   │       │   └── 3870112724rsegmnoittet-es.sqlite

│       │   │       └── .metadata-v2

│       │   └── temporary

│       ├── storage.sqlite

│       ├── times.json

│       └── xulstore.json

├── .vboxclient-clipboard.pid

├── .vboxclient-display-svga-x11.pid

├── .vboxclient-draganddrop.pid

├── .vboxclient-seamless.pid

└── .wget-hsts

1262 directories, 10126 files

Here, we have again used the bash tree command with the option “-a” to display the tree hierarchy of the specified directory “snap” in the bash shell. The snap directory displayed all the files in the tree format in the screenshot below.

tree –a ./snap

–a [error opening dir]

./snap [error opening dir]

0 directories, 0 files

tree command option “-f”: The usage of the -f flag with the tree command is to list the data of the directory together with the entire path prefix for each subdirectory and file. Here, we have used the tree command with the “-f” flag in the privilege of the sudo which asks for the root access permission of the logged user. The full path of the files and the subdirectories can be visualized in the given bash shell image.

$ sudo tree -f

[sudo] password for linux:

.

├── ./Bash Tree Command.docx

├── ./linux1.pdf

├── ./linux2.pdf

└── ./linux3.pdf

0 directories, 4 files

tree command option “-s”: Next, the tree command is used with the “-s” option. The option “-s” allows us to print not only the names of the files but also their sizes in bytes. In the following command of the tree, the flag “-f” is added first to take the hierarchy of the files and directories along with the path. Then, the “-s” flag is used to specify the size of that tree files and subdirectories.

$ tree –f -s

-f [error opening dir]

0 directories, 0 files

tree command option “-df”: The “d” option enables the tree command to generate the tree hierarchy of subdirectories without the filenames. We have established the tree command where the option “-d” and “-f” is combined to fetch the subdirectories with the full path.

$ sudo tree -df

0 directories

tree command option “-L”: The tree command “-L” option allows us specify the maximum number of folders fetched through the tree command. Limiting the depth is beneficial when we only need to explore the top few stages of extremely deep folder structures. In the following bash tree command, the “-L” option is given with the number “3” which indicates that three files or subdirectories can only be displayed in the tree hierarchy.

$ tree –L 3

–L [error opening dir]

3 [error opening dir]

Conclusion

The bash tree command helps figure out how the files are organized in our system. We first installed the tree command in the bash shell and then get a brief detail about the command using the man and help option. The tree command of bash has various options from which few are implemented in bash to explore the functionality of these options.

Share Button

Source: linuxhint.com

Leave a Reply