How to Compress and Extract Files using the tar command on Linux and How to create tar.gz file in Linux command line
Compress files
The tar command is used to pack and compress files and directories on Linux.
The archived files are usually named .tar.gz or .tgz and are called usually tarballs. As with many Linux commands, there are many options that can be used with the tar command.
Tar can compress and also extract .tar.gz or .tgz archives.
Example command to backup multiple directories into a tarball.
tar -czf /var/dibackup/backup-$datetxt.tar.gz /etc/ /home/ /var/www/ /var/dibackup/db-backup/
Here -czf means create a new archive, use gzip, specify the archive file name and compress the following files/directories – multiple paths are passed separated by space.
If you want to see more details about the process you can also use the -v option, v is for verbose listing of processed files.
tar -czvf /var/dibackup/backup-$datetxt.tar.gz /etc/ /home/ /var/www/ /var/dibackup/db-backup/
If you would like to exclude some directories you can use the –exclude option
tar -czvf /var/dibackup/backup-$datetxt.tar.gz /etc/ /home/ /var/www/ /var/dibackup/db-backup/ --exclude=/home/dragos/Downloads
Once finished, you will have a .tar.gz or .tgz file that is the archive.
Test – list archive contents
To list all files in the archive. Lists all files in archive-file.tgz verbosely.
tar -tvf archive-file.tgz
Extracting files from archive
When you need to extract the archive to the current directory you can use use the command bellow. Extracts all files from archive-file.tgz.
tar -xf archive-file.tgz
or to specify gzip
tar -xzf archive-file.tgz
or for verbose
tar -xzvf archive-file.tgz
Extract to directory
If you want the archive to be extracted to a specific directory you can use the -C option (capital C) change to directory DIR.
tar -xzf archive-file.tgz -C /home/dragos/archive-extracted
Using bzip2 instead of gzip
To use bzip2 compression instead of gzip, replace the -z option in the above commands with -j
tar command options used
Options used explanations:
-c, --create create a new archive
-z, --gzip, --gunzip, --ungzip filter the archive through gzip
-f, --file=ARCHIVE use archive file or device ARCHIVE
-v, --verbose verbosely list files processed
-t, --list list the contents of an archive
-j, --bzip2 filter the archive through bzip2
--exclude=PATTERN exclude files, given as a PATTERN
-C, --directory=DIR change to directory DIR
All command options
To see the available options you can see the man page or help or the tar command.
tar --help
man tar
If you are using Windows 10 or Windows 11 there is a good archiving tool called 7-Zip. You can use it to create or extract archives. Even archives created with tar on Linux.
Leave a Reply