Flash Sale:75% Off Hosting + Free DomainEnds in13h47m14sView Plans
Hostvento logoHostvento

Using the tar Command for File Compression

Create, compress, list and extract archives with tar.

How-To Guides2 min read5 screenshots

tar (tape archive) joins many files and folders into one archive file. With an option it also compresses the archive (gzip, bzip2 or xz).

Syntax

tar [options] [archive_name] [files_or_directories]

Main options

  • -c creates a new archive.
  • -x extracts files from an archive.
  • -t lists the contents of an archive.
  • -f gives the name of the archive file. Always put it last in a group of options, before the file name.
  • -v shows the files while it works (verbose).
  • -z compresses or decompresses with gzip (.tar.gz).
  • -j uses bzip2 (.tar.bz2).
  • -J uses xz (.tar.xz).
  • -r appends files to an existing, uncompressed archive.
  • -u adds files that are newer than those in the archive.
  • -A joins several archives.
  • -W verifies the archive after writing it.
  • -C changes to a folder before it extracts or creates.

Create an archive

tar -cvf archive.tar folder/
Creating a new tar archive

Create a compressed archive

gzip:

tar -czvf archive.tar.gz folder/
Creating a gzip-compressed tar archive

bzip2 (smaller, slower):

tar -cjvf archive.tar.bz2 folder/
Creating a bzip2-compressed archive

xz (smallest, slowest):

tar -cJvf archive.tar.xz folder/

List the contents

tar -tvf archive.tar.gz

Extract an archive

gzip archive in the current folder:

tar -xzvf archive.tar.gz
Extracting a gzip-compressed archive

Into a chosen folder:

tar -xzvf archive.tar.gz -C /path/to/folder

bzip2 archive:

tar -xjvf archive.tar.bz2

Any type (modern tar picks the compression by itself):

tar -xf archive.tar.xz
Extracting tar files in Linux

Extract one file:

tar -xzvf archive.tar.gz folder/file.txt

Add files to an archive

tar -rvf archive.tar newfile.txt

This works for uncompressed archives only.

Exclude files

tar -czvf backup.tar.gz --exclude='*.log' --exclude='node_modules' project/

Check an archive

tar -tzf archive.tar.gz > /dev/null && echo OK

Tips

  • Use absolute paths carefully. By default tar removes the leading / from paths.
  • Add a date to backup names: backup-$(date +%F).tar.gz.
  • Preserve permissions with -p when you extract as root.

Quick recap

  • Create: tar -czvf name.tar.gz folder/
  • Extract: tar -xzvf name.tar.gz
  • List: tar -tzvf name.tar.gz