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

Fix :: Linux SSH error "connection refused"

Problem Statement Can't connect to a Linux server(Debian Flavour) via SSH. Error Message...

bash: netstat: command not found.

You may face the below error on your Linux OS if you haven’t installed the netstat command...

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 add remote MySQL connection in linux?

Please refer to the following 3 steps to add a remote MySQL connection in Linux. Edit MySQL...

How to Install and Configure the HAProxy on CentOS?

HAProxy is a very fast and decent tool to achieve high availability, load balancing. It can work...

  • 0 Users Found This Useful

Was this answer helpful?