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

It is a very easy step to create archive files with .tar.gz or .tgz files. It is also called tarballs. There are various options with this command but we can use a few letters to create archives.

Compress an Entire Directory or a Single File

You can run the below command to compress a single file or an entire directory on Linux. It will also work recursively. Means, it will compress the other directories inside the directory that you have mentioned to compress.

tar -czvf myarchive-name.tar.gz /path/to/directory-or-file

Here, is the meaning of attributes in above commands.

  • -c: Create an archive file..
  • -z: Compress the archive file with gzip..
  • -v: You can use -v to display the progress in the terminal while creating the archive. It is also known as verbose mode..
  • It is optional in the above commands but could be helpful. .
  • -f: Specify the filename of the archive..

Suppose, there is a directory with the name mywork and you want to compress it with the name myarchive.tar.gz. You can run the following command.

tar -czvf myarchive.tar.gz mywork

In case, the directory is located at the /usr/local/mywork and you are looking to compress it with the file name myarchive.tar.gz then you can run the below command for this.

tar -czvf myarchive.tar.gz /usr/local/mywork

How to Compress Multiple Directories or Files?

tar -czvf myarchive.tar.gz /home/mysql_backup /usr/local/mywork /var/lib/mysql

You can list all the required directories or files as there are no limitations.

Extract an Entire Directory or a Single File

You can extract the archive file or folder with a similar tar command but slight changes. Below command will extract the compressed file myarchive.tar.gz

tar -xzvf myarchive.tar.gz

In case, you want to extract the compressed file to a specific location, you can run the below command. You need to specify the directory location where you want to extract the file.

tar -xzvf archive.tar.gz -C /home/mysql_backup

Related Articles

How to change SSH port on Ubuntu?

Please refer to the following steps to change the SSH port in Ubuntu. Login to your server via...

Do You Offer VPS with 8 vCPU Cores?

No, we do not provide VPS with 8 vCPU cores. We provide VPS with maximum 4 vCPU cores. This is...

How to Apply Linux Kernel Security Patches? Manually and Automatically without reboot?

As we know, we do receive Linux kernel updates time and time again and it is essential to update...

How to Install Tomcat 7 on Centos?

Tomcat is an open-source web server that is built in Java Servlet and JavaServer Pages...

How To Remotely Copy Files Over SSH Without Entering Your Password?

We can easily copy the files from one Linux machine to another using SSH. Here is an example of...

  • 0 Users Found This Useful

Was this answer helpful?