How Tar Works in Linux
Updated: Feb 6
The tar command in Linux is used to bundle up multiple files and/or directories. It's similar to the zip command. However, zip files are compressed by definition; tar files can be compressed, but don't have to be.
How to Use Tar on Linux
The basic command for creating tar.gz files is as below:
$ tar -czvf archivename.tar.gz filename...
-c is tells tar to create a new archive.
-z is sets the compression method to gzip.
-f archive-name.tar.gz specifies the name of archive.
filename... represents a list of files and directories to be added into the archive with space-separated. (for example :- filename1 filename2 )
The basic command for extracting a tar.gz files is as below:
$ tar -xzvf archivename.tar.gz
Create a Tar Archive
As an example, we create a Tar File named “example.tar.gz” with “filename1” and “filename2“
$ tar -czvf example.tar.gz filename1 filename2
The above command doesn’t show any output on success. So if we want verify that the archive is created or not, then list the directory contents with ls command.
If you wish to create the tar.gz inside a directory, then type full path to the archive file same as below:
$ tar -czvf /home/user/example.tar.gz filename1 filename2
Extract a Tar Archive
The following command will extract the contents of archive.tar.gz to the current directory.
tar -xzvf archive.tar.gz
We may want to extract the contents of the archive to a specific directory. We can do this by appending the -C switch to the end of the command. For example, the following command will extract the contents of the archive.tar.gz file to the /home directory.
tar -xzvf archive.tar.gz -C /home