It is a very easy step to create archive files with .tar.gz or .tgz files. It is also called tarballs. There are various options with this command but we can use a few letters to create archives.
Compress an Entire Directory or a Single File
You can run the below command to compress a single file or an entire directory on Linux. It will also work recursively. Means, it will compress the other directories inside the directory that you have mentioned to compress.
tar -czvf myarchive-name.tar.gz /path/to/directory-or-file
Here, is the meaning of attributes in 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 verbose mode..
- It is optional in the above commands but could be helpful. .
- -f: Specify the filename of the archive..
Suppose, 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
In case, the directory is located at the /usr/local/mywork and you are looking to compress it with the file name myarchive.tar.gz then you can run the below command for this.
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 slight changes. Below command will extract the compressed file myarchive.tar.gz
tar -xzvf myarchive.tar.gz
In case, you want to extract the compressed file to a specific location, you can run the below command. You need to specify the directory location where you want to extract the file.
tar -xzvf archive.tar.gz -C /home/mysql_backup