The tar command can be used to compress or extract one or more files in Linux. A tar file isn't actually a compressed format, instead it is a collection of files within a single file. The tar command can take one or more files, convert them into a tar file and then compress it into a gzip file format. The file created will have the extension tar.gz.
There are a large number of flags that can be used but the main ones for everyday use are.
- z : Use gzip compression to create a tar.gz file.
- c : Create a tar file.
- f : This is the name of the file to be used in the process of creation or extration.
- x : Extract or restore the file into the original file or files.
- v : Verbose. Report on every file extracted or added.
The verbose (v) flag can be useful when learning the tar command as it shows you everything that is going on with the process. This can cause things to slow down when compressing a large amount of files.
The command to create a compressed file from a directory is as follows. This will create an archive with the file name of archive.tar.gz from the directory passed.
tar -zcf archive.tar.gz directory
The command to extract an archive to a directory is as follows. This will extract an archive file called archive.tar.gz and restore it's original contents.
tar -zxf archive.tar.gz