Linux separates two jobs that other systems often combine. Archiving puts many files into one file. Compression makes a file smaller. tar does the first, gzip does the second.
gzip
gzip compresses a single file:
$ ls
notes.txt
$ gzip notes.txt
$ ls
notes.txt.gzNote that the original file is replaced. To restore it, run gunzip notes.txt.gz (or gzip -d notes.txt.gz). Use -k to keep the input file. Very old versions of gzip lack -k.
Creating a tar archive
$ tar -cvf project.tar project/
project/
project/main.c
project/README-ccreates an archive-vlists files as it works-f project.tarnames the archive file
The name must follow -f directly. A plain .tar file is not compressed.
Listing and extracting
Look inside before you extract:
$ tar -tf project.tar
project/
project/main.c
project/READMEThen unpack with -x:
$ tar -xf project.tarFiles land in the current directory and can overwrite files with the same names. Use -C to extract somewhere else. The directory must already exist:
$ mkdir restore
$ tar -xf project.tar -C restoretar with compression
tar can run the compressor for you. Add -z for gzip:
$ tar -czf project.tar.gz project/
$ tar -xzf project.tar.gz-j selects bzip2 (.tar.bz2) and -J selects xz (.tar.xz). These need the matching compression program installed. GNU tar, the usual version on Linux, detects the compression when reading from a file, so tar -xf project.tar.gz also works.
The short name .tgz means the same as .tar.gz.
Compression pays off on text such as source code and logs. Files that are already compressed, such as JPEG photos or most video, barely shrink.
Try it
$ mkdir demo
$ echo "hello" > demo/a.txt
$ tar -czf demo.tar.gz demo
$ tar -tzf demo.tar.gz
demo/
demo/a.txt
$ mkdir out
$ tar -xzf demo.tar.gz -C out
$ cat out/demo/a.txt
helloFor more practice, open the search and archives lab.
Check your understanding
tar and gzip
All 5 sections ยท no timer
Unlimited retries
Questions from every section are combined into one assessment. Answer them all correctly to complete the article.
Your completion saves in this browser. Sign in to sync it to your account.