blog.reifenrath.dev 7 min read Original Source

How to Back Up Your GNOME-Based Linux Desktop

Not a Medium member? Read here for free.

Losing your Linux desktop data can be catastrophic, backing up everything manually is annoying, and storing unsorted, duplicated backups is expensive. And what about encryption and security?

Borg Backup solved all of these issues for me, and the cherry on top: my passphrase for encrypting my backups is securely stored in GNOME’s integrated login keyring. This means high security without typing a passphrase every time I run my backup script.

This article explains how to set up the script for yourself and adapt it to your needs.

By the end, you’ll have:

  • encrypted, compressed, and deduplicated backups of everything you need to restore your system
  • key file and passphrase protection on your backups
  • no need to type in the passphrase manually
  • a convenient bash script to run your backups

What you need:

  • GNOME-based desktop environment
  • a hard drive or any other backup medium
  • and ideally a password manager

Plus, the software we will use and install during the tutorial:

  • Borg Backup version 1.4.4 or higher (not the 2.x beta version)
  • GNOME keyring
  • secret-tool
  • optional: GNOME “Passwords and Keys” (aka Seahorse)

Step 1: Installing Borg 1.x

For Ubuntu or Debian-based systems, run:

sudo apt install borgbackup
sudo apt install borgbackup

See Borg’s official documentation for other installation methods.

Verify your installation using:

borg --version
borg --version

Step 2: Setting up the Backup Repository

Borg uses repositories to store your backup archives. An archive is the result of a single backup. A single backup can contain multiple files and folders. The repository is simply a place to collect those archives.

First, create a folder on your backup drive. This is where your backups will be stored.

cd /run/media/user/ExternalHDD
mkdir Borg
cd Borg
mkdir DesktopBackups
cd /run/media/user/ExternalHDD
mkdir Borg
cd Borg
mkdir DesktopBackups

I created a folder /Borg with a subfolder /DesktopBackups, so that I can add more repositories to the same parent folder later, if I like.

The full repository is now: /run/media/user/ExternalHDD/Borg/DesktopBackups

Let’s initialize the repository right there:

borg init --encryption keyfile-blake2 /run/media/user/ExternalHDD/Borg/DesktopBackups
borg init --encryption keyfile-blake2 /run/media/user/ExternalHDD/Borg/DesktopBackups

I am setting the encryption mode to keyfile-blake2. keyfile will not only use a keyfile for encryption, but also allow you to set a passphrase. blake2 is a slightly faster encryption method than the default SHA-256. More details here.

The init command will ask you to set a passphrase. I recommend generating a strong passphrase using a password manager. Since you will never have to type it, it can be as complex as your password manager, and Borg can handle. I also save the passphrase to my password manager (Bitwarden), so that I have a backup of it.

After you copy and paste your passphrase twice, I would recommend answering the next question during initialization: “Do you want your passphrase to be displayed for verification? [yN]:”, with y, just to make sure nothing went wrong with copy-pasting or parsing.

Step 3: Exporting your Keyfile

When the init command is done, Borg conveniently tells you to export your keyfile and how to do so.

I used all three methods to export my keyfile to two thumb drives.

/run/media/user/ThumbDrive/key

borg key export –paper /run/media/user/ExternalHDD/Borg/DesktopBackups > /run/media/user/ThumbDrive/key.txt

borg key export –qr-html /run/media/user/ExternalHDD/Borg/DesktopBackups > /run/media/user/ThumbDrive/key.html” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

borg key export /run/media/user/ExternalHDD/Borg/DesktopBackups > /run/media/user/ThumbDrive/key

borg key export --paper /run/media/user/ExternalHDD/Borg/DesktopBackups > /run/media/user/ThumbDrive/key.txt

borg key export --qr-html /run/media/user/ExternalHDD/Borg/DesktopBackups > /run/media/user/ThumbDrive/key.html
borg key export /run/media/user/ExternalHDD/Borg/DesktopBackups > /run/media/user/ThumbDrive/key

borg key export --paper /run/media/user/ExternalHDD/Borg/DesktopBackups > /run/media/user/ThumbDrive/key.txt

borg key export --qr-html /run/media/user/ExternalHDD/Borg/DesktopBackups > /run/media/user/ThumbDrive/key.html

Step 4: Setting Up a CLI Secret Store

There are multiple ways to set up secret management for your passphrase, so that you don’t have to type it in every time. However, most methods either require you to set up additional authentication or expose your passphrase to logs or in your filesystem.

Also, as a minimalist (and lazy person!), I prefer to use what is already there. When I log in to my Ubuntu Desktop, I am already unlocking something with a password. That something is actually the GNOME Login Keyring, which I can see in the pre-installed “Passwords and Keys” tool, also called Seahorse:

To access that exact keyring in the CLI or from bash scripts, we can use secret-tool. This can be installed using:

sudo apt install libsecret-tools
sudo apt install libsecret-tools

Yes, we install the package libsecret-tools to install secret-tool. It’s not a typo. Verify your installation by just running secret-tool without any command or parameter.

Step 5: Setting Up your Passphrase

To store your passphrase you need to set a label and at least one attribute for it with secret-tool store.

secret-tool store --label="Borg DesktopBackups Passphrase" service borg repository desktopbackups
secret-tool store --label="Borg DesktopBackups Passphrase" service borg repository desktopbackups

I use two attributes:

  • service borg to give it the context I use it for
  • repository desktopbackups to have a unique identifier for this specific use case

When you execute the command, you will be asked to type or (better) paste your password.

After that, Seahorse will show you the new entry by the label and more importantly, you can access your passphrase from bash using:

secret-tool lookup service borg repository desktopbackups
secret-tool lookup service borg repository desktopbackups

This command will be used inside the backup script.

Step 6: Setting Up the Backup Script

&2; }
trap 'echo $( date ) Backup interrupted >&2; exit 2' INT TERM
info "Starting backup"
# Backup the most important directories into an archive named user-*
borg create
–dry-run
–verbose
–filter AMCE
–list
–stats
–show-rc
–exclude-caches
–exclude 'home/user/.steam'
–exclude 'home/user/.local/share/Steam'
–exclude 'home/user/.local/share/containers'
–exclude 'home/user/Downloads'
–exclude 'home/user/.cache'
–exclude 'home/user/.steam'
–exclude 'var/tmp'
–exclude 'var/cache'
–exclude 'var/run'

::'user-{now}'
/home/user
/etc
/var
/usr/local
/opt
backup_exit=$?
info "Pruning repository"
# Use the `prune` subcommand to maintain 7 daily, 4 weekly and 6 monthly
# archives of THIS machine. The 'user-*' matching is very important to
# limit prune's operation to this machine's archives and not apply to
# other machines' archives also:
borg prune
–dry-run
–list
–glob-archives 'user-*'
–show-rc
–keep-daily 7
–keep-weekly 4
–keep-monthly 6
prune_exit=$?
# actually free repo disk space by compacting segments
info "Compacting repository"
borg compact –dry-run
compact_exit=$?
# use highest exit code as global exit code
global_exit=$(( backup_exit > prune_exit ? backup_exit : prune_exit ))
global_exit=$(( compact_exit > global_exit ? compact_exit : global_exit ))
if [ ${global_exit} -eq 0 ]; then
info "Backup, Prune, and Compact finished successfully"
elif [ ${global_exit} -eq 1 ]; then
info "Backup, Prune, and/or Compact finished with warnings"
else
info "Backup, Prune, and/or Compact finished with errors"
fi
exit ${global_exit}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

#!/bin/sh

# 1. Exporting Environment Variables
# Setting this, so the repo does not need to be given on the commandline:
export BORG_REPO=/run/media/user/ExternalHDD/Borg/DesktopBackups
# See the section "Passphrase notes" for more infos.
export BORG_PASSCOMMAND='secret-tool lookup service borg repository desktopbackups'
# some helpers and error handling:
info() { printf "n%s %snn" "$( date )" "$*" >&2; }
trap 'echo $( date ) Backup interrupted >&2; exit 2' INT TERM
info "Starting backup"
# Backup the most important directories into an archive named user-*
borg create                                         
    --dry-run                                       
    --verbose                                       
    --filter AMCE                                   
    --list                                          
    --stats                                         
    --show-rc                                       
    --exclude-caches                                
    --exclude 'home/user/.steam'                    
    --exclude 'home/user/.local/share/Steam'        
    --exclude 'home/user/.local/share/containers'   
    --exclude 'home/user/Downloads'                 
    --exclude 'home/user/.cache'                    
    --exclude 'home/user/.steam'                    
    --exclude 'var/tmp'                             
    --exclude 'var/cache'                           
    --exclude 'var/run'                             
                                                    
    ::'user-{now}'                                  
    /home/user                                      
    /etc                                            
    /var                                            
    /usr/local                                      
    /opt
backup_exit=$?
info "Pruning repository"
# Use the `prune` subcommand to maintain 7 daily, 4 weekly and 6 monthly
# archives of THIS machine. The 'user-*' matching is very important to
# limit prune's operation to this machine's archives and not apply to
# other machines' archives also:
borg prune                          
    --dry-run                       
    --list                          
    --glob-archives 'user-*'        
    --show-rc                       
    --keep-daily    7               
    --keep-weekly   4               
    --keep-monthly  6
prune_exit=$?
# actually free repo disk space by compacting segments
info "Compacting repository"
borg compact --dry-run
compact_exit=$?
# use highest exit code as global exit code
global_exit=$(( backup_exit > prune_exit ? backup_exit : prune_exit ))
global_exit=$(( compact_exit > global_exit ? compact_exit : global_exit ))
if [ ${global_exit} -eq 0 ]; then
    info "Backup, Prune, and Compact finished successfully"
elif [ ${global_exit} -eq 1 ]; then
    info "Backup, Prune, and/or Compact finished with warnings"
else
    info "Backup, Prune, and/or Compact finished with errors"
fi
exit ${global_exit}
#!/bin/sh

# 1. Exporting Environment Variables
# Setting this, so the repo does not need to be given on the commandline:
export BORG_REPO=/run/media/user/ExternalHDD/Borg/DesktopBackups
# See the section "Passphrase notes" for more infos.
export BORG_PASSCOMMAND='secret-tool lookup service borg repository desktopbackups'
# some helpers and error handling:
info() { printf "n%s %snn" "$( date )" "$*" >&2; }
trap 'echo $( date ) Backup interrupted >&2; exit 2' INT TERM
info "Starting backup"
# Backup the most important directories into an archive named user-*
borg create                                         
    --dry-run                                       
    --verbose                                       
    --filter AMCE                                   
    --list                                          
    --stats                                         
    --show-rc                                       
    --exclude-caches                                
    --exclude 'home/user/.steam'                    
    --exclude 'home/user/.local/share/Steam'        
    --exclude 'home/user/.local/share/containers'   
    --exclude 'home/user/Downloads'                 
    --exclude 'home/user/.cache'                    
    --exclude 'home/user/.steam'                    
    --exclude 'var/tmp'                             
    --exclude 'var/cache'                           
    --exclude 'var/run'                             
                                                    
    ::'user-{now}'                                  
    /home/user                                      
    /etc                                            
    /var                                            
    /usr/local                                      
    /opt
backup_exit=$?
info "Pruning repository"
# Use the `prune` subcommand to maintain 7 daily, 4 weekly and 6 monthly
# archives of THIS machine. The 'user-*' matching is very important to
# limit prune's operation to this machine's archives and not apply to
# other machines' archives also:
borg prune                          
    --dry-run                       
    --list                          
    --glob-archives 'user-*'        
    --show-rc                       
    --keep-daily    7               
    --keep-weekly   4               
    --keep-monthly  6
prune_exit=$?
# actually free repo disk space by compacting segments
info "Compacting repository"
borg compact --dry-run
compact_exit=$?
# use highest exit code as global exit code
global_exit=$(( backup_exit > prune_exit ? backup_exit : prune_exit ))
global_exit=$(( compact_exit > global_exit ? compact_exit : global_exit ))
if [ ${global_exit} -eq 0 ]; then
    info "Backup, Prune, and Compact finished successfully"
elif [ ${global_exit} -eq 1 ]; then
    info "Backup, Prune, and/or Compact finished with warnings"
else
    info "Backup, Prune, and/or Compact finished with errors"
fi
exit ${global_exit}

The script consists of four parts: exporting environment variables, creating the archive, pruning, and compacting.

Note: I added --dry-run to all of the commands, so that you can try it out first without affecting your system. I recommend removing them one by one as you build up your script. Leaving the --dry-run on for borg prune and borg compact while you refine your script.

1. Exporting Environment Variables

To avoid passing the repository location and password on every borg command, we set up BORG_REPO and BORG_PASSCOMMAND at the beginning of the script. For BORG_PASSCOMMAND, we use the secret-tool command from step 5 to read our passphrase at execution time. This way, the passphrase won’t show in any logs or history.

2. Creating the Archive

To create the archive, we use borg create ::<ArchiveName> <path(s)/to/files/that/should/be/backed/up>. The attributes I use and that you should adapt to your needs:

  • --verbose: Show you that something is going on and what is going on.
  • --filter ACME: Filters the verbose output to show files that were added (A), created (C) or modified (M) and potential errors (E).
  • --stats: Prints statistics about the archives overall and added size.
  • --show-rc: Shows the return code. Very helpful in case of an error.
  • --exclude-caches: Excludes directories that include the CACHEDIR.TAG file.
  • --exclude: This is the first part that you will need to adapt to your needs. I exclude some default Linux caches: var/tmp, var/cache and var/run. My Steam installation and library get excluded to save on archive size and when something goes missing locally, I can re-download it anyway. For the same reason, I exclude docker-/podman-containers (home/user/.local/share/containers). My home/user/Downloads folder also acts as a cache for me, since I don’t keep anything there that should last.

Note: Don’t forget to change the /user in the path to your own username.

I give my archive the name of my user and the current date and time using the convenient {now} placeholder. There are also outer placeholders you can use. You could also use the {user} placeholder instead of hard-coding the user, like me.

After researching folders I should back up, I settled on /home/user, /etc, /var, /usr/local and /opt. This should include all kinds of system configurations and software I use on my programming and gaming desktop. For some users /root could be relevant. Here are two sources for inspiration:

3. Pruning

borg prune lets you set retention rules for your backups. I kept the defaults from their example script, which means 7 daily, 4 weekly and 6 monthly backups will be retained as set by the parameters --keep-daily 7 --keep-weekly --keep-monthly 6.

The other parameters are:

  • --list: shows you a list of your archives
  • --glob-archives 'user-*': Filters for all archives that start with user-, which we set in our borg create command. Other archives won’t be affected by this retention rule. Ensure you set this up correctly, because if the pattern does not match your archives, all archives could potentially be deleted.
  • --show-rc: Shows the return code for easier error handling.

Read the official documentation for more details.

4. Compacting

Since the prune command does not free disk space we need to run borg compact next to exactly that. It will also clean up any checkpoints created by intentionally or unintentionally aborting a backup.

Step 7: Enjoy!

Save your adapted bash script, give it a good name and execute it.

Remember to remove the --dry-run parameter on all borg commands, when ready for real use.

Support the Project

Borg is a powerful open-source tool. If you find it useful, consider donating to keep the project alive.

Thanks for reading!

If you found this guide helpful, feel free to leave a few claps 👏 to let me know. If you spot anything missing or deprecated, please leave a comment. I’ll do my best to keep this guide up to date.