初学者 Linux ar 命令教程(5 个示例)
在此页
- Linux ar 命令
- Q1。如何使用 ar 创建存档?
- Q2。如何使用 ar 列出存档的内容?
- Q3。如何直接显示存档中包含的文件内容?
- Q4。如何将新成员添加到存档?
- Q5。如何从存档中删除成员?
- 结论
在 Linux 中,有几个命令行实用程序可让您创建存档。一种这样的实用程序是 ar。在本教程中,我们将使用一些易于理解的示例来讨论此命令行工具的基础知识。但在此之前,值得一提的是,本文中包含的所有示例都已在 Ubuntu 18.04 LTS 机器上进行了测试。
Linux 命令
ar 命令允许您创建、修改或提取档案。以下是它的语法:
ar [OPTIONS] archive_name member_files
以下是手册页中关于此工具的内容:
The GNU ar program creates, modifies, and extracts from archives. An archive is a single file
holding a collection of other files in a structure that makes it possible to retrieve the original
individual files (called members of the archive).
The original files' contents, mode (permissions), timestamp, owner, and group are preserved in the
archive, and can be restored on extraction.
GNU ar can maintain archives whose members have names of any length; however, depending on how ar is
configured on your system, a limit on member-name length may be imposed for compatibility with
archive formats maintained with other tools. If it exists, the limit is often 15 characters
(typical of formats related to a.out) or 16 characters (typical of formats related to coff).
ar is considered a binary utility because archives of this sort are most often used as libraries
holding commonly needed subroutines.
ar creates an index to the symbols defined in relocatable object modules in the archive when you
specify the modifiers. Once created, this index is updated in the archive whenever ar makes a change
to its contents (save for the q update operation). An archive with such an index speeds up linking
to the library, and allows routines in the library to call each other without regard to their
placement in the archive.
以下是一些问答式的示例,应该可以让您对 AR 的工作原理有一个很好的了解。
Q1。如何使用 ar 创建存档?
您可以使用 r 命令选项执行此操作,根据手册页,该选项允许您“替换现有文件或将新文件插入存档。”
例如:
ar r test.a *.txt
上面的命令创建一个存档 test.a,其中包含当前目录中的所有 txt 文件。
Q2。如何使用 ar 列出存档的内容?
这可以使用 t 命令行选项来完成。因此,例如,运行以下命令:
ar t test.a
显示存档中包含的所有文件的列表。

Q3.如何直接显示存档中包含的文件内容?
这可以使用 p 命令选项来完成。这是一个例子:
ar p test.a
这是此命令产生的输出:

所以你可以看到所有三个文本文件的内容都显示在输出中(因为这些文件是彼此的副本,所以三种情况下的内容都是相同的)。
Q4.如何将新成员添加到存档?
r 命令选项也可以让您执行此操作。例如,要将新的文本文件 - tes3.txt - 添加到现有存档 test.a,我使用了以下命令:
ar r test.a test3.txt

Q5.如何从存档中删除成员?
这也很容易。只需使用 d 命令选项并指定要删除的成员的名称。
例如,要删除 test3.txt,我按以下方式使用 ar 命令:
ar d test.a test3.txt
以下截图显示文件已成功删除:

结论
当您想要创建或编辑档案时,ar 命令是一个方便的小工具。它还用于编程以创建程序链接到的静态库。我们只是触及了这里的表面。有关该工具的更多信息,请访问其手册页。