What I wanted to do

I wanted to archive files on a server for backup and compress logs to save disk space. Both tar and zip come up all the time, but I kept looking up the options every single time.

Basic tar commands

Create an archive (no compression)

tar -cvf archive.tar ./mydir
  • -c : create
  • -v : verbose output
  • -f : specify the filename

Create with gzip compression (.tar.gz)

tar -czvf archive.tar.gz ./mydir

Create with bzip2 compression (.tar.bz2)

tar -cjvf archive.tar.bz2 ./mydir

Extracting with tar

# Extract a .tar file
tar -xvf archive.tar

# Extract a .tar.gz file
tar -xzvf archive.tar.gz

# Extract a .tar.bz2 file
tar -xjvf archive.tar.bz2

# Extract to a specific directory
tar -xzvf archive.tar.gz -C /tmp/

List archive contents without extracting

tar -tzvf archive.tar.gz

Basic zip commands

# Compress files
zip archive.zip file1.txt file2.txt

# Compress a directory recursively
zip -r archive.zip ./mydir

# Set compression level (0-9, default is 6)
zip -r -9 archive.zip ./mydir

Extracting with unzip

# Extract to current directory
unzip archive.zip

# Extract to a specific directory
unzip archive.zip -d /tmp/output

# List contents without extracting
unzip -l archive.zip

Common patterns

Archive logs with a date stamp

tar -czvf "logs-$(date +%Y%m%d).tar.gz" /var/log/nginx/

Exclude specific files or directories

tar -czvf archive.tar.gz ./mydir --exclude='*.log' --exclude='node_modules'

Check compression ratio

ls -lh archive.tar.gz
du -sh ./mydir

Gotchas

  • The -f flag in tar must come last in the option string — the filename immediately follows -f
  • Forgetting -r in zip -r means the directory contents won’t be included
  • .tar.gz and .tgz are the same format, so either extension works fine with the same options
  • unzip may not be installed on a fresh Linux server — install it with apt install unzip
  • Using absolute paths with tar can cause files to extract to unexpected locations; be aware of leading / in paths

Looking for reliable cloud infrastructure? Check out these developer-friendly services.