Intermediate · 8 min · practise every command in the built-in terminal

tar — Tape Archive

tar combines multiple files into a single archive (and optionally compresses them).

Creating archives

tar -cvf archive.tar directory/          # Create archive
tar -czvf archive.tar.gz directory/     # Create + gzip compress
tar -cjvf archive.tar.bz2 directory/   # Create + bzip2 compress
tar -cJvf archive.tar.xz directory/    # Create + xz compress

Flags: c=create, v=verbose, f=filename, z=gzip, j=bzip2

Extracting archives

tar -xvf archive.tar                    # Extract
tar -xzvf archive.tar.gz               # Extract gzip
tar -xjvf archive.tar.bz2             # Extract bzip2
tar -xvf archive.tar -C /target/dir   # Extract to directory

Flags: x=extract, C=change directory

Listing contents (without extracting)

tar -tvf archive.tar
tar -tzvf archive.tar.gz

Compress a single file

gzip file.txt          # Creates file.txt.gz, removes original
gunzip file.txt.gz     # Decompress
gzip -k file.txt       # Keep original
gzip -d file.txt.gz    # Same as gunzip

Quick memory trick

  • create, extract, test (list)
  • z = gzip (.gz), j = bzip2 (.bz2), J = xz (.xz)
  • Always include f (filename) and v (verbose) while learning

Practice tasks

  1. Create a compressed tar.gz archive of your documents/ directory
  2. List the contents of your archive without extracting
  3. Extract the tar.gz archive you created
  4. Compress a single file with gzip

Commands in this lesson

Archives & Compression