The tar command in Linux allows you to compress files and directories into tar.gz files, also known as tarballs. They are very useful in data archival and compression. Here’s how to create tar.gz file in Linux.
How to create tarball in Linux
We will use the tar command to create tar.gz file in Linux. Here’s the syntax
$ tar -cvzf filename.tar.gz /path/to/file [paths to more files/directories] OR $ tar -cvzf filename.tar.gz /path/to/directory [paths to more files/directories]
In the above command, the tar command is followed by options -cvzf, the filename of final tar.gz file to be created, followed by one or more paths to files/directories
In the above command we mention the following options
- c – creation of archive file
- v – for verbose, meaning it will display the progress in terminal
- z – gzip the archived .tar file
- f – filename of archive file
Bonus Read : How to Create Zip and Unzip File in Linux
Let us look at a few examples to create tar.gz file
Here’s the command to create tar.gz file (e.g sales_data.tar.gz) from a single file (e.g /home/ubuntu/sales_data.txt)
$ tar -cvzf sales_data.tar.gz /home/ubuntu/sales_data.txt
First tar command will create the archive .tar file and then compress it to create .tar.gz file. That is why you see 2 file extensions in a tarball.
Bonus Read : How to Find Directory in Linux
How to create a tar.gz file from a directory
Here’s the tar command to create tar.gz file from a directory (e.g /home/ubuntu/product/)
$ tar -cvzf product.tar.gz /home/ubuntu/product/ /home/ubuntu/product/ /home/ubuntu/product/file1.txt /home/ubuntu/product/file2.exe /home/ubuntu/product/file3.pdf
tar command will list contents of your directory that is being archived.
Bonus Read : How to List all files in a Directory in Linux
How to Extract tar.gz file
Here’s the command to extract tar.gz file
$ tar -xvf product.tar.gz /home/ubuntu/product/ /home/ubuntu/product/file1.txt /home/ubuntu/product/file2.exe /home/ubuntu/product/file3.pdf
tar command will list the contents of your tar.gz file that is being extracted.
In the above command, we use -x option for extraction, instead of using -c for compression. Other options are same as above.
Here’s the command to extract files to a specific directory (e.g /home/ubuntu/data)
$ tar -xvf filename.tar.gz /path/to/dir
$ tar -xvf product.tar.gz /home/ubuntu/data
Hopefully, the above tutorial will help you create tarball as well as extract tar.gz files in Linux.