バッシュツリーコマンド
bashのtreeコマンドは、ファイルとディレクトリをリスト表示するために使用されるLinuxのよく知られたlsコマンドに匹敵します。コマンド間の主な違いは、treeコマンドによってファイルとフォルダがツリー状の構造で表示されることです。treeコマンドはファイル階層を繰り返し処理し、深さのインデントで書式設定されたリストでファイルとサブディレクトリを印刷します。bashのtreeコマンドを使用すると、ファイルとフォルダの位置を迅速に確認し、アクセス権を調べ、隠しファイルやディレクトリも取得できます。
例 # 1: Bashでのツリーのインストール。
treeコマンドはbashの組み込みコマンドではありません。bashシェルで呼び出す前に、treeコマンドをインストールする必要があります。treeモジュールをbash内にインストールするために、aptコマンドとsudo権限を使用します。インストールのコマンドが実行されると、認証のためのパスワードが要求され、その後bashにtreeがインストールされます。ここでは、すでに最新バージョンのtreeコマンドをインストールしています。
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) ...現在、ツリーコマンドは私たちのシステムにインストールされたため、bash内で使用できます。次のコマンドは、ツリーコマンドのバージョンを確認するために使用されます。このコマンドは、私たちのシステムにインストールされた最新のツリーのバージョンを返しました。
tree –version
tree v1.8.0 (c) 1996 - 2018 by Steve Baker, Thomas Moore, Francesc Rocher, Florian Sesser, Kyosuke Tokorobashのtreeコマンドに関するヘルプを得るには、次のtreeコマンドを「–help」オプションと共に実行します。これにより、bashシェルでのtreeコマンドに関連するすべての必要な情報が画像のようにリストされます。
tree –help
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.
さらに、“man”キーワードを使用してtreeコマンドを実行することで、treeコマンドの詳細情報を得ることもできます。
tree man例#2:Bashでtreeコマンドを使用する。
ツリーコマンドのインストールプロセスは上記のセクションで完了しました。今、bashでツリーコマンドを使用するには、bashシェルに「tree」というキーワードを入力するだけです。「tree」コマンドは、指定したディレクトリの内容をツリー形式で表示します。ここでは、引数なしでツリーコマンドを実行しました。引数なしでツリーコマンドを実行すると、現在のパスにあるすべてのファイルとディレクトリのツリー構造が表示されました。この画像は、私たちのホームパスのファイルと、それらのファイルを持つディレクトリをツリー構造で示しています。最後に、私たちのホームディレクトリ内にあるディレクトリとファイルの合計が表示されました。
tree
├── linux1.pdf
├── linux2.pdf
└── linux3.pdf
0 directories, 3 files出力は、“less” キーワードを使用して tree コマンドを使うことで、より読みやすくすることができます。これは、ディレクトリ内のすべてのファイルとフォルダをリストしたいときに便利です。以下に示す tree コマンドでは、現在のディレクトリ内のファイルとフォルダを見るために、tree キーワードと共にスラッシュ “/” シンボルを使用しています。その後、“|” パイプラインシンボルを使用して、“less” キーワードを指定しています。画像内では、いくつかのフォルダとファイルが木構造の形式でリストされているのがわかります。コロン “:” は最後にあり、押すと現在のディレクトリの追加のフォルダとファイルが表示されます。
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
:bashのtreeコマンドは、プロセスツリーを表示するためにも使用できます。以下のコマンドでは、「proc」は現在のディレクトリで実行中のプロセスを表します。treeコマンドを実行するためにEnterを押すと、bashシェルで私たちのディレクトリのツリープロセスが生成されます。
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例 # 3: Bashで異なるオプションを使用したTreeコマンド。
tree command option “-a”:treeコマンドは、bashでさまざまなオプションをサポートしており、このセクションでは各treeコマンドオプションのパフォーマンスを示すために使用しました。まず、オプション「-a」を使用してtreeコマンドを実行しました。「-a」オプションは、bashシェルの画像に表示される隠しファイルを含むディレクトリ内のすべてのファイルを取得しました。
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ここでは、bashシェルで指定されたディレクトリ「snap」のツリー階層を表示するために、オプション「-a」を使ってbashのtreeコマンドを再度使用しました。スナップディレクトリは、以下のスクリーンショットのようにツリーフォーマットで全てのファイルを表示しました。
tree –a ./snap
–a [error opening dir]
./snap [error opening dir]
0 directories, 0 filestreeコマンドオプション「-f」: treeコマンドの-fフラグを使用すると、各サブディレクトリとファイルの完全なパスプレフィックスと共に、ディレクトリのデータをリストすることができます。ここでは、ログインユーザーのルートアクセス権限を要求するsudoの権限で-treeコマンドを-fフラグと共に使用しています。ファイルとサブディレクトリの完全なパスは、指定されたbashシェルの画像で視覚化することができます。
sudo tree -f
[sudo] password for linux:
.
├── ./Bash Tree Command.docx
├── ./linux1.pdf
├── ./linux2.pdf
└── ./linux3.pdf
0 directories, 4 filestree コマンドオプション “-s ”: 次に、tree コマンドは “-s ” オプションで使用されます。オプション “-s ” を使用すると、ファイルの名前だけでなく、そのサイズもバイト単位で表示できます。次の tree コマンドでは、最初にフラグ “-f ” が追加され、ファイルおよびディレクトリの階層とともにパスが取得されます。その後、“-s ” フラグが使用され、ツリーのファイルとサブディレクトリのサイズを指定します。
tree –f -s
-f [error opening dir]
0 directories, 0 files
tree コマンドオプション “-df”:“d” オプションは、tree コマンドがファイル名なしでサブディレクトリのツリー階層を生成できるようにします。私たちは、サブディレクトリを完全なパスで取得するために、オプション “-d” と “-f” を組み合わせた tree コマンドを確立しました。
sudo tree -df
0 directoriestree コマンドオプション “-L ”: tree コマンドの “-L ” オプションは、tree コマンドを通じて取得するフォルダーの最大数を指定できます。深さを制限することは、非常に深いフォルダー構造の上位の数段階だけを探索する場合に有益です。次の bash tree コマンドでは、“-L ” オプションに数値 “3 ” が指定されており、それはツリーの階層で三つのファイルやサブディレクトリのみを表示できることを示しています。
tree –L 3
–L [error opening dir]
3 [error opening dir]結論
bashのtreeコマンドは、システム内のファイルの整理方法を把握するのに役立ちます。まず、bashシェルにtreeコマンドをインストールし、次にmanおよびhelpオプションを使用してコマンドの簡単な詳細を取得しました。bashのtreeコマンドにはさまざまなオプションがあり、その中のいくつかは、これらのオプションの機能を探るためにbashに実装されています。