On Windows and macOS, compressing files into a .zip archive is as simple as right-clicking a folder. In the Linux terminal, however, you must use command-line utilities. The most ubiquitous archiving tool in the Linux ecosystem is tar (Tape Archive).
Almost every software package, source code download, or backup file you encounter on an Ubuntu server will be packaged as a .tar.gz file (often called a “tarball”). Here is everything you need to know to compress and extract files using the tar command.
Step 1: Understand the Flags
The tar command relies heavily on “flags” (letters with a dash in front of them) to know what action you want it to perform. You will combine these flags into a single string. Here are the five most important ones:
- -c : Create a new archive.
- -x : Extract an existing archive.
- -z : Compress the archive using gzip (this makes the file size significantly smaller).
- -v : Verbose mode (prints the names of the files to the screen as it works, so you know it hasn’t frozen).
- -f : File name (this must be the very last flag, followed immediately by the name of the archive).
Step 2: Compress a Folder into a Tarball
Let’s say you have a directory named /var/www/html/website, and you want to back it up into a single, compressed file before making changes.
- Open your terminal.
- Type the
tarcommand, followed by the creation flags (-czvf), then the name you want to give the new archive, and finally, the folder you want to compress:
tar -czvf website_backup.tar.gz /var/www/html/website - Press Enter.
Because you included the -v flag, your terminal will scroll rapidly, listing every single file as it compresses them. When the prompt returns, you will have a new file named website_backup.tar.gz in your current directory.
Step 3: Extract a Tarball
Now, assume you downloaded a piece of software named software_v2.tar.gz and you need to unpack it so you can install it.
- Open your terminal and navigate to the folder where the file is located.
- To extract it, you will swap the create flag (
-c) for the extract flag (-x). Type the following:
tar -xzvf software_v2.tar.gz - Press Enter.
The tar utility will instantly decompress the file and extract its contents into a new folder within your current directory.
Step 4: Extract to a Specific Location
By default, tar extracts files exactly where you are currently standing in the terminal. If you want to unpack a file into a completely different directory (for example, extracting web files directly into /var/www/), you must use the capital -C flag.
- Type the extract command, append the
-Cflag at the end, and then specify the destination path:
tar -xzvf website_backup.tar.gz -C /var/www/ - Press Enter.
By mastering these basic tar commands, you can easily manage server backups, transfer large amounts of data, and install custom software on any Ubuntu machine.