Skip to content
Français
Sync not enabled: your progress stays in this browser My learning
Select theme
Français

Archive and compress files on Linux

By updated

Improve this page

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 / unzip for cross-platform sharing

Archiving vs compressing: what is the difference?

OperationWhat it doesMain tool
ArchiveGroups several files into a single filetar
CompressReduces the size of a filegzip, 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:

Terminal window
tar -cvf backup.tar /home/bob/projects/
OptionMeaning
-cCreate an archive
-vVerbose, show the files processed
-fFile, 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:

Terminal window
tar -tvf backup.tar

Extract 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.

Terminal window
tar -xvf backup.tar
OptionMeaning
-xExtract

To extract into a given directory:

Terminal window
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:

Terminal window
gzip file.log

The 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:

Terminal window
gzip -k file.log

The -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.

Terminal window
gunzip file.log.gz

Or, equivalently:

Terminal window
gzip -d file.log.gz

How 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

Terminal window
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

Terminal window
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

Terminal window
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.

ExtractionPermissionsOwner
user, without -pfiltered by the umaskwhoever extracts
user, with -pkeptwhoever extracts
root, with -pkeptrestored

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:

Terminal window
sudo tar --selinux --xattrs -cf conf.tar /etc/myservice
sudo 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.

Terminal window
tar -xzvf backup.tar.gz # gzip
tar -xjvf backup.tar.bz2 # bzip2
tar -xJvf backup.tar.xz # xz

Summary 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.

OptionCompressionExtension
-zgzip (fast).tar.gz
-jbzip2 (generally better than gzip, slower).tar.bz2
-Jxz (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.

Terminal window
zip archive.zip file1.txt file2.txt

To archive a whole folder (recursively):

Terminal window
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.

Terminal window
unzip archive.zip

To extract into a given directory:

Terminal window
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.

Terminal window
unzip -l archive.zip

Install 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.

Terminal window
sudo apt install zip unzip

Which 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.

NeedCommand
Back up a folder (Linux ↔ Linux)tar -czvf archive.tar.gz folder/
Share with Windows/macOSzip -r archive.zip folder/
Compress a single file (log, dump)gzip file
Extract a .tar.gztar -xzvf archive.tar.gz
Extract a .zipunzip 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.

ProblemLikely causeFix
tar: Cannot open: No such file or directoryWrong pathCheck the path with ls
tar: Removing leading '/' from member namesAbsolute path storedNormal behaviour, a safety measure against overwriting
gzip: notes.txt.gz already has .gz suffix -- unchangedFile already compressedgzip leaves it as is: no need to compress it again
unzip: cannot find or openFile missing or wrong nameCheck the exact name with ls
Very large archives are too slowxz compression on a big folderUse gzip (-z), which is faster
Permission denied on extractionNo permission to writeExtract 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

  • tar archives (groups), gzip compresses (reduces the size).
  • tar -czvf does both in a single command, the most common case.
  • The extension compresses nothing: tar cf archive.tar.gz produces a raw archive, whereas tar -czvf or tar caf really compress.
  • zip is the universal format for cross-platform sharing.
  • Always check the contents of an archive with -tvf or unzip -l before extracting.
  • To compress a single file: gzip file (and gunzip to 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

6 questions
6 min
70% to pass

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