As described in the manual page, the ar (archiver) command is used to create, modify, and extract from archives. In this article, we learn about this command through various examples.
Table of contents.
- Command usage.
An archive is a collection of files with a common structure. We use the ar command to create, modify and extract individual files from an archive.
We write ar commands using the following format:
$ ar [OPTIONS] archive-file file...
1. Creating an archive
To create a new archive we write:
$ ar r [archive file] [file(s)]
For example to create a new archive called textfiles.a and place all .txt files in the archive we write:
$ ar r textfiles.a *.txt
Now, let's add a new file to the archive:
$ ar r textfiles.txt newFile.txt
In the above example, we have added the file newFile.txt to the archive.
2. Printing archive.
To print the archive members we use the p option followed by the name of the archive:
$ ar p [archive name]
The above command will print all contents of the files in the archive.
To print the archive contents in a list format, we use the t.
$ ar t [archive name]
3. Extracting from an archive:
We use the -x option to extract from an archive. Here we name the file to be extracted, however, if we don't, all members of the archive will be extracted.
Extract single file:
$ ar x [archive name] [file name]
For to extract a file called bootLogs.txt from an archive textfiles.a we write:
$ ar x textfiles.a bootLogs.txt
Extract multiple files we just list them as arguments to the ar command:
$ ar x [archive name] [file1 file2 file3...]
Extract all files:
$ ar x [archive name]
4. Deleting a file in an archive.
To delete a file from an archive we use the d option as follows:
$ ar d [archive name] [file]
To delete multiple files, all we have to do is list the files
$ ar d [archive name] [file1 file2 file3...]
5. Reading contents of archived files.
To read the contents of an archive, we combine the -p option with the -v option. This is demonstrated below:
$ ar pv [archive name]
As an alternative we can also use the tar command to archive files in Linux, however, note that archiving is not the same as compressing. With compression, we make the file size smaller by re-encoding the file data to utilize less storage space, and later we can decompress it. Here we use complex mathematical algorithms. With archiving, we just place common files into a single file without any bit manipulation.
For a comprehensive guide on how to use this command, we can check out its manual by executing the command: $ man ar.