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.ymlEach 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.gzExtracting 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
Exercise: Bash Archives
What does the `tar` command do by default, before any compression flag is added?