Linux系统之tree命令的基本使用

发布于:2025-02-11 ⋅ 阅读:(51) ⋅ 点赞:(0)

在这里插入图片描述

一、tree命令介绍

tree 是一个递归列出目录内容的命令行实用工具,它以树状图的形式显示文件和目录结构。tree 命令不是 Linux 系统默认自带的命令,需要单独安装。

二、tree工具安装

  • 安装 tree

  • 在大多数基于 Debian 的系统(如 Ubuntu)上,可以通过以下命令安装 tree

sudo apt-get update
sudo apt-get install tree
  • 对于基于 Red Hat 的系统(如 CentOS 或 Fedora),可以使用以下命令:
sudo yum install tree
# 或者在较新的版本中使用
sudo dnf install tree

三、tree命令帮助

3.1 查询帮助信息

在Rocky Linux 9.4系统中,我们在命令行终端使用–help选项查询tree命令帮助信息。

[root@RockyLinux-server001 ~]# 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.
  --du          Print directory sizes.
  --prune       Prune empty directories from the output.
  ------- 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.

3.2 tree命令帮助解释

  • 使用方法:
tree [选项]... [<directory list>]
  • 列表选项
选项 描述
-a 列出所有文件,包括隐藏文件。
-d 仅列出目录。
-l 将符号链接当作目录处理。
-f 打印每个文件的完整路径前缀。
-x 保持在当前文件系统内,不进入其他文件系统(如挂载点)。
-L level 递归显示指定深度的目录层级。
-R 当达到最大目录层级时重新运行 tree
-P pattern 仅列出匹配给定模式的文件。
-I pattern 不列出匹配给定模式的文件。
--ignore-case 模式匹配时忽略大小写。
--matchdirs -P 模式匹配中包含目录名。
--noreport 关闭树状图结尾处的文件/目录计数。
--charset X 使用字符集 X 输出终端/HTML 和缩进线。
--filelimit # 如果目录中的文件数量超过 #,则不深入该目录。
--timefmt <f> 根据格式 打印和格式化时间。
-o filename 输出到文件而不是标准输出。
--du 打印目录大小。
--prune 从输出中剪除空目录。
  • 文件选项
选项 描述
-q 将不可打印字符显示为 ?
-N 直接打印不可打印字符。
-Q 使用双引号引用文件名。
-p 打印每个文件的权限。
-u 显示文件所有者或用户ID (UID)。
-g 显示文件所属组或组ID (GID)。
-s 打印每个文件的字节数大小。
-h 以更易读的方式打印文件大小。
--si 类似于 -h,但使用 SI 单位(1000 的幂)。
-D 打印最后一次修改日期或(使用 -c)状态更改日期。
-F 根据 ls -F 的方式添加后缀 /=, *, @, `
--inodes 打印每个文件的 inode 号。
--device 打印每个文件所属设备 ID 号。
  • 排序选项
选项 描述
-v 按版本对文件进行字母数字排序。
-t 按最后修改时间排序文件。
-c 按最后状态改变时间排序文件。
-U 不对文件排序。
-r 反转排序顺序。
--dirsfirst 先列出目录再列出文件(-U 禁用此功能)。
--sort X 选择排序方式:名称、版本、大小、修改时间、状态改变时间。
  • 图形选项
选项 描述
-i 不打印缩进线。
-A 使用 ANSI 线条图形打印缩进线。
-S 使用 CP437 控制台图形打印缩进线。
-n 总是关闭颜色化(-C 覆盖此选项)。
-C 总是开启颜色化。
  • XML/HTML/JSON 选项
选项 描述
-X 打印树状结构的 XML 表示。
-J 打印树状结构的 JSON 表示。
-H baseHREF 以 HTML 格式打印,baseHREF 作为顶级目录。
-T string 使用字符串替换默认的 HTML 标题和 H1 标签。
--nolinks 关闭 HTML 输出中的超链接。
  • 输入选项
选项 描述
--fromfile 从文件中读取路径(. 表示标准输入)。
  • 杂项选项
选项 描述
--version 打印版本信息并退出。
--help 打印用法和此帮助信息并退出。
-- 选项处理终止符。

四、tree命令的基本使用

4.1 直接使用

最简单的用法是直接输入 tree,这将从当前目录开始,显示所有子目录和文件。

[root@RockyLinux-server001 ~]# tree
.
├── aa
├── aa01.txt
├── aa02.txt
├── aa03.txt
├── aa04.txt
├── aa05.txt
├── aa06.txt
├── abc.txt
├── anaconda-ks.cfg
├── mytest.aa
├── test.txt
└── tree
    └── bb
        └── cc

3 directories, 11 files

4.2 *限制显示的层级

我们可以使用 -L 选项来指定要显示的最大深度。

[root@RockyLinux-server001 ~]# tree -L 1
.
├── aa
├── aa01.txt
├── aa02.txt
├── aa03.txt
├── aa04.txt
├── aa05.txt
├── aa06.txt
├── abc.txt
├── anaconda-ks.cfg
├── mytest.aa
├── test.txt
└── tree

1 directory, 11 files

4.3 仅显示目录

如果你只想看到目录而不包括文件,可以使用 -d 选项。

[root@RockyLinux-server001 ~]# tree -d
.
└── tree
    └── bb
        └── cc

3 directories

4.4 不显示隐藏文件

  • 默认情况下,tree 不会显示隐藏文件(即以点.开头的文件)。如果你不想改变这个行为,只需要正常使用 tree 即可。

  • 如果想明确地确保隐藏文件不会被显示,可以使用 -a-I 选项结合来排除特定模式:

  • 以下面的例子会显示所有文件,但排除 .git.ssh 目录。

[root@RockyLinux-server001 ~]# tree -a -I '.git|.ssh'
.
├── aa
├── aa01.txt
├── aa02.txt
├── aa03.txt
├── aa04.txt
├── aa05.txt
├── aa06.txt
├── abc.txt
├── anaconda-ks.cfg
├── .bash_history
├── .bash_logout
├── .bash_profile
├── .bashrc
├── .cshrc
├── .docker
│   └── buildx
│       ├── activity
│       │   └── default
│       ├── .buildNodeID
│       ├── defaults
│       ├── instances
│       ├── .lock
│       └── refs
│           └── default
│               └── default
│                   └── l719wavztb8rg53q0s8243nep
├── .lesshst
├── mytest.aa
├── .tcshrc
├── test.txt
├── tree
│   └── bb
│       └── cc
└── .viminfo

11 directories, 23 files

4.5 显示文件大小

使用 -h 选项可以让 tree 显示文件大小,并且是以人类易读的方式(例如 KB, MB)。

[root@RockyLinux-server001 ~]# tree -h
.
├── [   58]  aa
├── [    0]  aa01.txt
├── [    0]  aa02.txt
├── [    0]  aa03.txt
├── [    0]  aa04.txt
├── [    0]  aa05.txt
├── [    0]  aa06.txt
├── [   12]  abc.txt
├── [  978]  anaconda-ks.cfg
├── [   15]  mytest.aa
├── [   79]  test.txt
└── [   16]  tree
    └── [   16]  bb
        └── [    6]  cc

3 directories, 11 files
 ```

4.6 彩色输出

使用 -C 选项可以让 tree 输出带有颜色的文本,使输出更加直观。

[root@RockyLinux-server001 ~]# tree -C
.
├── aa
├── aa01.txt
├── aa02.txt
├── aa03.txt
├── aa04.txt
├── aa05.txt
├── aa06.txt
├── abc.txt
├── anaconda-ks.cfg
├── mytest.aa
├── test.txt
└── tree
    └── bb
        └── cc

3 directories, 11 files
 ```

4.7 输出到文件

如果想要保存 tree 的输出结果,可以重定向输出到文件。

     tree > directory_structure.txt

4.8 输出不同格式

例如使用-J选项和,可以输出json格式内容。

[root@RockyLinux-server001 ~]# tree -J
[{"type":"directory","name": ".","contents":[
    {"type":"file","name":"aa"},
    {"type":"file","name":"aa01.txt"},
    {"type":"file","name":"aa02.txt"},
    {"type":"file","name":"aa03.txt"},
    {"type":"file","name":"aa04.txt"},
    {"type":"file","name":"aa05.txt"},
    {"type":"file","name":"aa06.txt"},
    {"type":"file","name":"abc.txt"},
    {"type":"file","name":"anaconda-ks.cfg"},
    {"type":"file","name":"mytest.aa"},
    {"type":"file","name":"test.txt"},
    {"type":"directory","name":"tree","contents":[
      {"type":"directory","name":"bb","contents":[
        {"type":"directory","name":"cc","contents":[
        ]}
      ]}
    ]}
  ]},
  {"type":"report","directories":3,"files":11}
]

五、注意事项

  1. tree 命令不是所有 Linux 发行版默认安装的工具,可能需要通过包管理器手动安装。

  2. 使用 -a 选项显示隐藏文件时,请注意这可能会列出大量你通常不需要查看的系统文件。

  3. 在大目录结构中使用 tree 可能会产生非常庞大的输出,建议结合管道和分页工具如 less 使用。

  4. 如果不希望 tree 递归进入其他挂载点下的文件系统,可以使用 -x 选项限制在当前文件系统内。

  5. 使用 -L 选项可以限制 tree 的递归深度,这对于只想查看顶层结构或特定层级内容非常有用。

  6. tree 支持多种输出格式,包括彩色终端输出、HTML、XML 和 JSON,适用于不同的应用场景。

  7. 当需要处理包含非打印字符的文件名时,使用 -N-Q 选项可以帮助正确显示或引用这些文件名。

  8. 对于性能考虑,可以通过 --filelimit 选项设置最大文件数量,避免 tree 在大型目录中消耗过多资源。

  9. 使用 --prune 选项可以简化输出,排除空目录,使树状图更加简洁。

  10. tree 的排序和过滤选项允许用户根据需求定制化输出,但要注意这些操作可能增加命令执行的时间。


网站公告

今日签到

点亮在社区的每一天
去签到