You need to back up a configuration folder, send a project to a colleague or free up disk space. On Linux, two moves cover these needs: archiving (grouping several files into one) and compressing (reducing the size). This guide shows you the essential commands: tar, gzip and zip.
What you will learn
- Tell apart archiving and compression
- Create and extract an archive with
tar - Compress a file with
gzip - Combine archiving and compression with
tar -czvf - Use
zip/unzipfor cross-platform sharing
Archiving vs compressing: what is the difference?
| Operation | What it does | Main tool |
|---|---|---|
| Archive | Groups several files into a single file | tar |
| Compress | Reduces the size of a file | gzip, bzip2, xz |
In practice you often do both at once: tar archives + gzip compresses → a .tar.gz file.
The difference shows on a folder of 200 files. gzip * compresses each file separately and produces 200 .gz files, which simplifies neither the transfer nor the backup. To get a single compact file, you archive first with tar, then compress: that is what tar -czvf does, presented further down.
tar: archive files
tar (Tape Archive) groups files and directories into a single .tar file. It keeps the tree, the permissions and the dates.
Create an archive
This command archives the /home/bob/projects/ folder into the backup.tar file:
tar -cvf backup.tar /home/bob/projects/| Option | Meaning |
|---|---|
-c | Create an archive |
-v | Verbose, show the files processed |
-f | File, the name of the archive to create |
The order of the arguments matters: the archive name comes right after -f, and the files to archive come next. Swap them and the result depends on what comes first. With a directory, tar refuses (Cannot open: Is a directory). With an existing file, tar may overwrite it with the archive, and its original content is then lost: that is the classic beginner's mistake with tar, and the reason to reread your command before you run it. Remember too that -f is easy to forget, and that without it tar writes to standard output.
List the contents of an archive
Before extracting, check what the archive contains:
tar -tvf backup.tarExtract an archive
A single letter changes compared with creation: -x replaces -c. The rest of the command is identical, which explains how a typo can destroy an archive instead of opening it. Extraction drops the files in the current directory, not in their original location: if you run the command from your home, the archive's tree appears there.
tar -xvf backup.tar| Option | Meaning |
|---|---|
-x | Extract |
To extract into a given directory:
tar -xvf backup.tar -C /tmp/restore/To exclude files, make incremental backups or transfer over SSH, the advanced tar guide takes over, and the tar reference sheet summarises the options.
gzip: compress a file
gzip compresses a single file. It replaces the original file with its compressed .gz version:
gzip file.logThe file file.log.gz is created and file.log disappears.
Keep the original
Replacing the source file is the default behaviour of gzip, and it often surprises people the first time. On a log file you are still analysing, or on a dump you want to keep readable, add -k:
gzip -k file.logThe -k (keep) option keeps the original file. You then end up with file.log and file.log.gz, so with the disk space of both.
Decompress
Two commands do exactly the same thing. With GNU gzip, gunzip is not a separate program: it is a small shell script that calls gzip -d. In both cases, the .gz file disappears in favour of the decompressed file, with the same replacement logic as compression.
gunzip file.log.gzOr, equivalently:
gzip -d file.log.gzHow do you archive and compress in one command?
In practice, you combine tar and a compressor in a single command. It is the most common case.
Create a compressed .tar.gz archive
tar -czvf backup.tar.gz /home/bob/projects/The -z option enables gzip compression. It is the most widespread combination on Linux, to the point that .tar.gz and its short form .tgz mean the same thing. In general, gzip compresses faster than the next two formats, at the cost of a slightly larger archive.
Create a .tar.bz2 archive
tar -cjvf backup.tar.bz2 /home/bob/projects/The -j option enables bzip2 compression. This format compresses better than gzip but stays slow to decompress, and it is nobody's default choice any more: xz and zstd have largely replaced it. You will mostly meet it on old archives that you need to be able to open.
Create a .tar.xz archive
tar -cJvf backup.tar.xz /home/bob/projects/The -J option (upper case) enables xz compression. Watch the case: lower-case -j is bzip2, upper-case -J is xz, and the two look alike in a command line read too quickly. xz generally produces the smallest archives of the three, at the cost of clearly higher compression time and memory use on large volumes.
Does tar really keep permissions?
The claim "tar keeps permissions" needs two nuances before you rely on it for a restore, and they depend on who extracts.
Without -p, an extraction by an ordinary user filters the permissions through their umask. A file archived as 0666 comes out as 644 under a umask 022. The -p option (--preserve-permissions) restores the original permissions, and it is implicit when root extracts.
The owner, for its part, is never restored outside root, even with -p: the files belong to the account that extracts. It is a kernel constraint, not a tar one.
| Extraction | Permissions | Owner |
|---|---|---|
user, without -p | filtered by the umask | whoever extracts |
user, with -p | kept | whoever extracts |
root, with -p | kept | restored |
Why does a restored file lose its SELinux context?
On RHEL, AlmaLinux or Fedora, an archive restored outside its original location loses its SELinux label: a file labelled etc_t comes out as user_home_t, and the service that was supposed to read it is blocked by a Permission denied that Unix permissions do not explain.
You need --selinux --xattrs on both sides, at creation and at extraction:
sudo tar --selinux --xattrs -cf conf.tar /etc/myservicesudo tar --selinux --xattrs -xf conf.tar -C /Failing that, a restorecon -R on the destination after extraction puts back the labels the policy expects.
Extract according to the format
When reading, GNU tar detects the compressor on its own by inspecting the first bytes of the file: tar -xvf backup.tar.gz works without -z. The letters below remain useful for two reasons: they document the expected format, and they make the command fail if the file is not what you think, which is better than silently extracting the wrong type.
tar -xzvf backup.tar.gz # gziptar -xjvf backup.tar.bz2 # bzip2tar -xJvf backup.tar.xz # xzSummary of the tar options
Three letters to remember, and one criterion to choose: compression time against final size. For a daily backup replayed often, -z remains the right compromise. For an archive written once and kept for a long time, -J generally gives the smallest archive. If you do not want to memorise this table, -a deduces the right option from the extension you give.
| Option | Compression | Extension |
|---|---|---|
-z | gzip (fast) | .tar.gz |
-j | bzip2 (generally better than gzip, slower) | .tar.bz2 |
-J | xz (generally the best ratio of the three, the slowest) | .tar.xz |
zip / unzip: cross-platform compatibility
The ZIP format is recognised by Windows, macOS and Linux. It is the format to prefer when you share files with users on other systems.
Create a ZIP archive
Unlike tar, zip compresses each file separately before putting them together. The compression ratio is therefore a little worse on a batch of similar small files, but extracting a single item does not require reading the whole archive. Another difference in behaviour: zip is not recursive by default. A folder passed without -r only adds the folder entry itself, without its contents, and unzip -l then shows an archive with a single 0-byte item.
zip archive.zip file1.txt file2.txtTo archive a whole folder (recursively):
zip -r archive.zip folder/Extract a ZIP archive
unzip extracts into the current directory and asks for confirmation before overwriting an existing file, file by file. On a large archive, this interactive prompt blocks a script: in that case, -o overwrites without asking and -n never replaces anything.
unzip archive.zipTo extract into a given directory:
unzip archive.zip -d /tmp/extraction/List the contents
The reflex is the same as with tar -tvf: look before extracting. The output gives each entry's uncompressed size, its date and its path. Watch that path: an entry in ../ or an absolute path signals a dubious archive. unzip refuses to leave the current directory, and then prints skipped "../" path component(s) or stripped absolute path spec, but an archive that triggers these messages deserves a look at where it came from.
unzip -l archive.zipInstall zip and unzip
Neither zip nor unzip is part of minimal installations on RHEL and derivatives, whereas tar and gzip are always there. Check they are present with command -v zip before writing a script that depends on them, otherwise the failure will only occur in production, on the least equipped server.
sudo apt install zip unzipsudo dnf install zip unzipWhich archive command should you choose?
The choice comes down to one criterion: who will read the archive. Between Linux machines, tar keeps permissions, symbolic links and the tree: it is the format to use for a backup you can restore. As soon as a Windows or macOS workstation enters the loop, zip opens with a double click without installing anything. Enter the table through the row that describes your situation; the command on the right can be copied as is.
| Need | Command |
|---|---|
| Back up a folder (Linux ↔ Linux) | tar -czvf archive.tar.gz folder/ |
| Share with Windows/macOS | zip -r archive.zip folder/ |
| Compress a single file (log, dump) | gzip file |
Extract a .tar.gz | tar -xzvf archive.tar.gz |
Extract a .zip | unzip archive.zip |
Troubleshooting
tar's messages are terse, and one of them is not an error. Removing leading '/' from member names is a protection, not a failure: tar strips the leading / so that a careless extraction does not overwrite /etc on the destination machine. On the other hand, any message containing Broken pipe or Child returned status signals a missing compressor, and the archive produced is unusable even if it exists on disk.
| Problem | Likely cause | Fix |
|---|---|---|
tar: Cannot open: No such file or directory | Wrong path | Check the path with ls |
tar: Removing leading '/' from member names | Absolute path stored | Normal behaviour, a safety measure against overwriting |
gzip: notes.txt.gz already has .gz suffix -- unchanged | File already compressed | gzip leaves it as is: no need to compress it again |
unzip: cannot find or open | File missing or wrong name | Check the exact name with ls |
| Very large archives are too slow | xz compression on a big folder | Use gzip (-z), which is faster |
Permission denied on extraction | No permission to write | Extract into /tmp or use sudo |
Put it into practice
The options of tar get mixed up quickly as long as you have not typed them yourself. In this lab, you create gzip and bzip2 archives, list their contents with -tvf and extract a single file into a target directory: exactly the moves of a real restore.
Key points
tararchives (groups),gzipcompresses (reduces the size).tar -czvfdoes both in a single command, the most common case.- The extension compresses nothing:
tar cf archive.tar.gzproduces a raw archive, whereastar -czvfortar cafreally compress. zipis the universal format for cross-platform sharing.- Always check the contents of an archive with
-tvforunzip -lbefore extracting. - To compress a single file:
gzip file(andgunzipto decompress).
Knowledge check
Check that the essentials of this guide stuck. The questions cover only what has just been explained here.
Knowledge check
Check what you have learned with this interactive quiz
How it works
- The timer starts when you click Start
- Multiple choice, true/false and short answer questions
- You can move between questions
- Detailed results are shown at the end
Starts the quiz and the timer
Review
(0/0)Result saved on this device. It will be sent to your account at the next sync. Sync now
Score by domain
A domain groups several guides and gets several questions, so its score is more reliable than a per-topic score, which often rests on a single question.
Summary
Strengths
No topic passed at 80% on at least two questions yet.
Weak areas
No topic below the pass mark.
Recommended next
Hints before you try again?
Continue the course: Nano: edit, save and exit a file
A new full quiz with random questions
Work again only on the questions you missed