The tar command is a powerful tool used to create archives by grouping multiple files into a single file. The name “tar” comes from “tape archive,” as archives were originally stored on tapes. In this guide, we will explore various ways to use the tar command effectively.

Creating an Archive

To create an archive with the name archive.tar and include file1 and file2, you can use the following command:

tar -cf archive.tar file1 file2

Here, the -c option signifies the creation mode, and the -f option is used to specify the output file as the archive.

Extracting Files from an Archive

To extract files from an archive in the current directory, use the command:

tar -xf archive.tar

The -x option denotes the extraction mode. If you want to extract the files to a specific directory, you can use the -C option followed by the directory path, as shown below:

tar -xf archive.tar -C directory

Listing Files in an Archive

To view the files contained in an archive without extracting them, use the following command:

tar -tf archive.tar

This command will display a list of files included in the archive.

Creating Compressed Archives

The tar command can also be used to create compressed archives by using the z option. This option gzip’s the archive. To create a gzipped archive named archive.tar.gz with file1 and file2, use the following command:

tar -czf archive.tar.gz file1 file2

This command creates a tar archive first and then runs gzip on it. You can also use the j option instead of z to create a Bzip2 compressed archive.

Extracting Compressed Archives

To unarchive a gzipped archive, you can use the tar command directly. For example, to extract archive.tar.gz, simply run:

tar -xf archive.tar.gz

The tar command automatically recognizes that it is a gzipped archive and extracts the files accordingly.

Compatibility

The tar command works seamlessly on Linux, macOS, WSL (Windows Subsystem for Linux), and anywhere you have a UNIX-like environment.