How to Compress and Extract Files Using the tar Command on Linux

If you’re working on a Linux system, you may have come across compressed files with a “.tar” extension. These files are created using the tar command, which is a utility used to create and extract archives on Linux systems. In this article, we’ll explain how to use the tar command to compress and extract files on your Linux system.

Compressing Files with the tar Command

Step 1: Open the Terminal Open the terminal on your Linux system by pressing the Ctrl+Alt+T keys.

Step 2: Navigate to the Directory Navigate to the directory where the files you want to compress are located using the cd command.

Step 3: Compress the Files Use the following command to compress the files in the directory into a single tar archive:

tar -cvf archive_name.tar file1 file2 file3

The “c” option tells tar to create a new archive, the “v” option displays the files being added to the archive, and the “f” option tells tar that the next argument is the name of the archive.

Step 4: Verify the Archive You can verify that the archive has been created by using the following command:

bash
ls -l

This will show you the list of files in the directory, including the newly created archive file.

Extracting Files with the tar Command

Step 1: Open the Terminal Open the terminal on your Linux system by pressing the Ctrl+Alt+T keys.

Step 2: Navigate to the Directory Navigate to the directory where the tar archive is located using the cd command.

Step 3: Extract the Files Use the following command to extract the files from the tar archive:

tar -xvf archive_name.tar

The “x” option tells tar to extract the files from the archive, the “v” option displays the files being extracted, and the “f” option tells tar that the next argument is the name of the archive.

Step 4: Verify the Files You can verify that the files have been extracted by using the following command:

bash
ls -l

This will show you the list of files in the directory, including the newly extracted files.

Compressing and Extracting Multiple Directories and Files

You can also use the tar command to compress and extract multiple directories and files. To compress multiple directories and files, use the following command:

tar -cvf archive_name.tar directory1 directory2 file1 file2

To extract multiple directories and files, use the following command:

tar -xvf archive_name.tar

This will extract all the directories and files in the archive to the current directory.

Using the tar command on Linux can be a quick and easy way to compress and extract files. Whether you need to backup files, transfer files between systems, or just save disk space, the tar command is a powerful tool that can help you get the job done.