Bash Tar Archives

Learn how to bundle and compress files into a .tar.gz archive with tar -czvf, and reverse it with tar -xzvf.

Creating Archives with tar -czvf

tar was originally built for writing streams of files to tape, and that streaming design is still why it is the standard way to bundle a Linux directory tree into one file. On its own tar only concatenates files; adding -z pipes that stream through gzip, producing the familiar .tar.gz format.

Example

$ tar -czvf project-backup.tar.gz ./project
project/
project/src/
project/src/main.sh
project/README.md
project/config.yml

Each letter in -czvf does one job: c creates a new archive, z compresses the stream with gzip, v prints each file as it's added (verbose), and f names the archive file that follows. f must come last in the flag group, right before the filename, because tar expects the very next argument after f to be that filename.

Example

$ du -sh ./project
48M     ./project
$ ls -lh project-backup.tar.gz
-rw-r--r-- 1 dev dev 11M Jul 16 14:40 project-backup.tar.gz

Extracting with tar -xzvf

Extraction mirrors creation: swap -c for -x and the same z, v, f letters apply. tar extracts into the current directory by default, but -C redirects the output to any directory of your choice, which is useful for restoring into a fresh location instead of overwriting the original.

Example

$ tar -xzvf project-backup.tar.gz -C /tmp/restore
project/
project/src/
project/src/main.sh
project/README.md
project/config.yml
  • -c creates a new archive
  • -x extracts an existing archive
  • -z compresses or decompresses with gzip
  • -j compresses or decompresses with bzip2 instead of gzip
  • -v prints each file as it's processed (verbose)
  • -f specifies the archive filename, and must come last
  • -C DIR extracts into DIR instead of the current directory
  • -t lists an archive's contents without extracting
FlagDescription
-cCreate a new archive
-xExtract files from an existing archive
-zFilter the archive through gzip
-vPrint each file name as it is processed
-fSpecify the archive's filename, always last in the group
-CChange to the given directory before extracting
Note: Run tar -tzvf project-backup.tar.gz to list what's inside an archive without extracting anything, a safe first step before unpacking a file you didn't create.
Note: Swapping -z for -j switches compression to bzip2 (tar -cjvf), which usually produces a smaller file at the cost of more CPU time. -z remains the everyday default because it's faster and universally supported.

Exercise: Bash Archives

What does the `tar` command do by default, before any compression flag is added?