Skip to content

Instantly share code, notes, and snippets.

@HaleTom
Last active March 9, 2017 11:42
Show Gist options
  • Save HaleTom/9dbffaf3369b86ca272ffe6a61a36aba to your computer and use it in GitHub Desktop.
Save HaleTom/9dbffaf3369b86ca272ffe6a61a36aba to your computer and use it in GitHub Desktop.
Safely backup pacman's sync databases
#!/bin/bash
# Safely backup the pacman databases to enable reversal of system upgrade.
# Use pacman -b <backupdirectory> to use the saved databses
# Latest version: https://gist.github.com/HaleTom/9dbffaf3369b86ca272ffe6a61a36aba
set -euo pipefail; shopt -s failglob # safe mode
db_lock=/var/lib/pacman/db.lck
source_dir=/var/lib/pacman/sync
target_dir=/var/lib/pacman/backup/$(date --iso-8601=seconds)
function warn { >&2 echo "$(basename "$0"): " "$@"; }
function die { warn "$@"; exit 1; }
function remove_lock {
if [[ -d $db_lock ]]; then
rmdir "$db_lock" || warn "Can't remove DB lock: $db_lock"
fi
}
# Make sure DB lock is obtained and released
mkdir --mode=000 "$db_lock" || die "Can't acquire DB lock: $db_lock"
trap 'remove_lock' EXIT HUP INT TERM # Automatically clean up the lock
# Backup source directory
mkdir -p "$target_dir" || die "Can't create target directory $target_dir"
cp --archive --reflink=auto --interactive "$source_dir"/* "$target_dir"
# Save lists of explicitly installed (not dependencies) packages
pacman -Qe > "$target_dir"/packages-all
pacman -Qne > "$target_dir"/packages-native
pacman -Qme > "$target_dir"/packages-foreign
echo pacman package lists and sync databases saved to: "$target_dir"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment