How to: Backup or sync files with 7-Zip CLI

Last update: Dec 2017

Motivation

Sometimes we just want to backup files with very simple tools in order to keep it simple and stupid. Although it’s well documented, many people do not know, that the 7-Zip command line tool can also update the backup target in case some files changed within the source.

Environment

  • Works on almost any Linux or Windows
  • Tested on: Windows 10

Requirements

  • Basic knowledge about Windows’ or Linux’ command line
  • for Ubuntu: package p7zip-full installed
  • for Windows: 7-Zip CLI executable available (7za.exe)

Steps

1. The single-line command

Short and beautiful:

# command for windows
path/to/7za.exe a -up0q0r2x1y1z1w2 -mx1 "path/to/archive.7z" "path/to/source"

If you need the command for Linux, just substitute the program path with a simple “7z”.

2. Explaining the parameters

  • path/to/7za.exe: Your place where 7za.exe is stored.
  • a: Command to ADD files/folders to an archive.
  • -up0q0r2x1y1z1w2: Options which actually enable 7-Zip to work as expected. This holy string consists of:
  • -u parameter UDPATE
  • p0 condition P: What to do if file exists in archive, but is not matched with wildcard? 0 = Ignore file (don’t create item in new archive for this file).
  • q0 condition Q: NOT in source, but IN archive > 0 = Ignore file.
  • r2 condition R: IN source, but NOT in archive > add and compress file.
  • x1 condition X: in source OLDER, than in archive > copy file from old to new archive.
  • y1 condition Y: in source NEWER, than in archive > copy file from old to new archive.
  • z1 condition Z: file is identical > copy file from old to new archive.
  • w2 condition W: same time but different size > add and compress file.
  • -mx1 I prefer to determine the level of compression. It’s saving some time for data which is already highly compressed like movies, pictures and music.
    Possible Values: 0 (none) | 1 (fast) | 3 (fast) | 5 (normal) | 7 (maximum) | 9 (ultra). Newer benchmarks are showing the time/compression ratio is best at level 3.
  • “path/to/archive.7z” Where the archive has to be stored. If your path contains any spaces, be sure to use quotation marks.
  • “path/to/source” Your file/folder which should be copied (recursively). Use quotation marks if there are spaces inside your path.

By the way: There is a very good documentation for 7-Zip out there.

Credits