While Windows users typically rely on ZIP files to bundle and compress data, the Linux world has long favoured the “tarball.” A tar archive is a single file containing multiple files and directories, preserving their complex permissions and ownership structures. By itself, the tar command only bundles files together; it does not shrink them. To save disk space or bandwidth, you must combine tar with a compression algorithm like gzip or bzip2.
Understanding the Tar Command Syntax
The tar command uses a string of flag letters to determine its exact behaviour. The most common flags used for creating archives are:
- c: Create a new archive.
- v: Verbose mode (displays the files being processed on the screen).
- f: Specifies the filename of the archive you are creating.
- z: Compress the archive using the gzip algorithm (creating a
.tar.gzfile). - j: Compress the archive using the bzip2 algorithm (creating a
.tar.bz2file).
How to Create a Gzip Compressed Archive (.tar.gz)
Gzip is the undisputed standard for compression in Linux. It offers an excellent balance between compression speed and file size reduction. This is the format you should use 95% of the time.
- Open your terminal in Ubuntu.
- Use the following command structure:
tar -czvf archive_name.tar.gz /path/to/directory
For example, if you want to compress a folder named “project_files” located in your home directory into an archive named “backup.tar.gz”, you would type:
tar -czvf backup.tar.gz ~/project_files
The terminal will list all the files scrolling by as they are bundled and compressed into the new backup.tar.gz file in your current working directory.
How to Create a Bzip2 Compressed Archive (.tar.bz2)
If file size is your absolute highest priority and you are willing to sacrifice compression speed to achieve it, you can use bzip2 instead of gzip. It generally results in a smaller final archive but takes significantly longer to process.
- Open the terminal.
- Swap the
-zflag for the-jflag:tar -cjvf archive_name.tar.bz2 /path/to/directory
For example: tar -cjvf heavy_backup.tar.bz2 ~/massive_database_folder
How to Extract a Compressed Archive
When you eventually need to restore the files from your tarball, the command is nearly identical, except you replace the “create” flag (-c) with the “extract” flag (-x).
To unpack a .tar.gz file: tar -xzvf archive_name.tar.gz
To unpack a .tar.bz2 file: tar -xjvf archive_name.tar.bz2
The contents will be instantly extracted into your current directory.