Compress backups with tar and 7-Zip
tar and 7z commands to create, encrypt, test and extract backup archives, and to estimate their size.
This article collects common commands for compressing backups with tar on Linux and 7-Zip (7z) on Windows, and for estimating the size of an archive without extracting it.
Backup with tar
Example script that archives a dated web directory and moves it to a backup disk:
#!/bin/bash
# Backup of important data
DATE=$(date +"%d-%b-%Y")
cd /var/www/
tar -zcvf HTML-$DATE.tgz html
mv *.tgz /mnt/backup/html
Main tar options:
| Option | Purpose |
|---|---|
c |
Create an archive |
x |
Extract an archive |
t |
List archive contents |
f |
Use the file given as parameter |
v |
Verbose mode (shows progress) |
z |
gzip compression |
j |
bzip2 compression |
J |
xz (lzma) compression |
tar cfvj files.tar.bz2 files
tar -tvf file.tar
tar -xzvf archive.tar.gz -C /tmp
7-Zip archive
Create an encrypted 7z archive with encrypted headers:
"C:\Program Files\7-Zip\7z.exe" a -t7z -m0=lzma2 -mx=5 -ms=on -mhe=on -p<PASSWORD> D:\backup\archive.7z D:\data\*
| Option | Purpose |
|---|---|
a |
Add files to the archive |
-t7z |
7z format |
-m0=lzma2 |
LZMA2 compression method |
-mx=N |
Compression level (0 to 9) |
-ms=on |
Solid archive |
-mhe=on |
Header encryption (file names are protected) |
-r |
Recurse into subdirectories |
-xr!pattern |
Exclude files matching the pattern |
Test and extract:
7z t -p<PASSWORD> archive.7z
7z x -p<PASSWORD> -o.\extract\ archive.7z
Estimate the size without extracting
gzip -l archive.tar.gz
zcat archive.tar.gz | wc --bytes
bzcat archive.tar.bz2 | wc -c
unrar l archive.rar
unzip -l archive.zip
gzip -l shows the compressed and uncompressed sizes and the compression ratio. For .tar.gz and .tar.bz2 files, piping through wc gives the size of the uncompressed stream.
Notes
- Do not type the password on the command line: it stays visible in the shell history and the process list. With
-pand no value, 7-Zip prompts for the password. - Header encryption (
-mhe=on) hides the file names without the password, but every operation on the archive then requires the password.