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

Creating archive files with .tar, .gz, or .tgz files is easy; it is also called Tarballs

This command has various attributes, we can use it to create archives.

Compress an Entire Directory or a Single File

You can run the command given below to compress a single file or an entire directory on Linux. It will also work recursively, i.e., compress other directories inside the directory you mentioned in the command.

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

Here is the meaning of attributes in the 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 a verbose mode. It is optional in the above commands but could be helpful.
  • -f: Specify the filename of the archive.

If 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

If the directory is located at the /usr/local/mywork and you want to compress it with the file name myarchive.tar.gz, then you can run this command – 

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 with slight changes. 

By executing the command given below, you can extract the compressed file myarchive.tar.gz – 

tar -xzvf myarchive.tar.gz

Suppose you want to extract the compressed file to a specific location. In that case, you can run the command below and specify the directory location where you want to extract the file – 

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



Was this answer helpful?

« Back

chat