How to compress and extract files using tar command in Linux
The tar command in Linux is often used to create .tar.gz or .tgz archive files. This command has a large number of options, but you just need to remember a few letters to quickly create archives with tar. The tar command can extract the resulting archives, too.
Compress an Entire Directory or a Single File
Use the following command to compress an entire directory or a single file on Linux. It will also compress every other directory inside a directory you specify – in other words, it works recursively.
tar -czvf name-of-archive.tar.gz /path/to/directory-or-file
Here’s what those switches actually mean:
- -c: Create an archive.
- -z: Compress the archive with gzip.
- -v: Display progress in the terminal while creating the archive, also known as “verbose” mode. The v is always optional in these commands, but it’s helpful.
- -f: Allows you to specify the filename of the archive.
If you have a directory named ‘data’ in the current directory and you want to save it to a file named archive.tar.gz , you would run the following command:
tar -czvf archive.tar.gz data
If you have a directory at /usr/local/something on the current system and you want to compress it to a file named archive.tar.gz , you would run the following command:
tar -czvf archive.tar.gz /usr/local/something
Extract an Archive
Once you have an archive, you can extract it with the tar command. The following command will extract the contents of archive.tar.gz to the current directory.
tar -xzvf archive.tar.gz
It’s the same as the archive creation command we used above, except the -x switch replaces the -c switch. This specifies you want to extract an archive instead of create one.
You may want to extract the contents of the archive to a specific directory. You can do so 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 /tmp directory.
tar -xzvf archive.tar.gz -C /tmp