When you need to email ten separate log files to a developer, or download the source code for a massive open-source project, transferring hundreds of individual files over a network is incredibly inefficient. Every single file creates a new network request, slowing the transfer to a crawl. To solve this, Linux relies on the legendary tar command.
The tar command (which stands for Tape Archive) acts like a digital cardboard box. It takes hundreds of loose files and directories, packs them into a single, neat container, and optionally crushes that container down to a fraction of its original size using compression. In this guide, you will learn how to pack and unpack these crucial archives.
Step 1: Creating a Compressed Archive
While tar can simply bundle files together without compressing them, it is almost always used in conjunction with “gzip” compression. The resulting file will end with the extension .tar.gz.
To pack an entire folder named “website_backup” into a single compressed file, use this syntax:
tar -czvf backup_2023.tar.gz /var/www/website_backup/
You must understand what those four flags actually do:
- -c (Create): Tells the system you are creating a brand new archive.
- -z (Zip): Tells the system to compress the archive using gzip, drastically reducing the file size.
- -v (Verbose): Forces the command to print out the name of every file as it gets packed, so you can visually confirm the progress.
- -f (File): This flag is mandatory and must be the absolute last letter. It tells the system that the very next word you type (backup_2023.tar.gz) is the name you want to give the new file.
Step 2: Viewing the Contents of an Archive
If someone emails you a mysterious .tar.gz file, you should never blindly extract it without seeing what is inside first. It could contain a massive directory tree that overwrites your local files.
To peek inside the digital box without opening it, replace the -c (Create) flag with the -t (List) flag:
tar -tzvf mysterious_file.tar.gz
This will simply print a safe, text-based list of every file hidden inside the archive.
Step 3: Extracting the Archive
Once you have verified the contents and are ready to unpack the files onto your hard drive, you use the -x (Extract) flag.
tar -xzvf backup_2023.tar.gz
By default, this command will dump all the files directly into whatever folder you are currently standing in. If you want to unpack the files into a completely different directory, you can add the -C (Change Directory) flag at the very end of the command:
tar -xzvf backup_2023.tar.gz -C /home/user/documents/
By mastering the tar command, you ensure that you can safely bundle, compress, and transport massive amounts of data across any Linux system with maximum efficiency.