• This is basically the config from home.file

Setup

  1. Install home-manager
  2. Create a directory called ~/backups to store the symlinks to backups

(the actual data will be stored in /nix/store)

Backing up a file

  • Add this to your ~/.config/nixpkgs/home.nix:
home.file = {
  example = {
    source = "/path/to/file";
    target = "backups/example";
  };
};
  • run home-manager switch

Result

$ cat example
> hello world

$ cat backups/example
> hello world

$ ls -l backups/example
> backups/example -> /nix/store/...home-manager-files/backups/example

Backing up a directory

home.file = {
  exampleDir = {
    source = "/path/to/example-directory";
    target = "backups/example-directory";
    recursive = true;
  };
};

Result

$ ls example-directory/
> example  example2

$ ls backups/example-directory/
> example@  example2@

$ ls -l backups/example-directory/
> example -> /nix/store/..home-manager-files/backups/example-directory/example
> example2 -> /nix/store/..home-manager-files/backups/example-directory/example2

Adding a Script

home.file = {
  exampleScript = {
    source = "/path/to/script";
    target = "backups/script";
    executable = true;
  };
};

Running commands on file change

  • This will always run if recursive is set to true
home.file = {
  exampleDir = {
    source = "/path/to/example-directory";
    target = "backups/example-directory";
    recursive = true;
    onChange = "echo $(date) >> /tmp/modified"
  };
};
  • Result:
$ cat /tmp/modified
> Sat Feb 26 21:57:40 PST 2022

Restoring from backups

$ rm example # Whoops!

$ cat backups/example > example

$ cat example
> hello world

Deleting Backups

$ vim ~/.config/nixpkgs/home.nix # remove the entry from home.nix

$ home-manager switch

# the symlink in `~/backups` is gone but the data is still in /nix/

# store to remove it run:

$ nix-collect-garbage -d

Deduplication

$ cd example-directory

$ diff example example2

# huh, these files have the same content, why store it twice? run:

$ nix-store --optimise