Allow +<number> when using nix-collect-garbage
I need NixOS to automatically delete all old generations when collecting garbage (to free disk space) and only keep a specific number of generations to boot from.
The nix-env command accepts a +<number> when deleting generations.
Check: https://nixos.org/manual/nix/stable/command-ref/nix-env/delete-generations
But nix-collect-garbage does not accept a +<number> argument 😦
Check: https://nixos.org/manual/nix/stable/command-ref/nix-collect-garbage
sudo nix-collect-garbage --delete-older-than +2 results in an error =>
error: invalid number of days specifier '+2', expected something like '14d'
And adding this to the configuration.nix will also result in an error =>
nix.gc.options = "--delete-older-than +2";
Which means it is currently not possible to let NixOS automatically delete all generations (when garbage collecting) and only leave the last 2 generations (for example).
So my feature request would be letting the nix-collect-garbage command accept a +<number> argument.
(similar to nix-env --delete-generations +<number>)
For anyone finding this, here's my workaround (use at your own risk)
nix.gc = {
automatic = true;
dates = "weekly";
};
# clean up generations before garbage collecting
systemd.services.nix-gc.wants = [ "nix-gen-gc.service" ];
# automatic generation garbage collection
systemd.services.nix-gen-gc = {
description = "NixOS Generation Garbage Collector";
# keep 10 generations + any future generations
script = "exec ${config.nix.package.out}/bin/nix-env -vvvv --profile /nix/var/nix/profiles/system --delete-generations +10";
serviceConfig.Type = "oneshot";
};
+1 for this. The current nix-collect-garbage workflow is essentially "delete everything or delete nothing," which makes managing disk space on developer machines unnecessarily stressful.
Being able to say nix-collect-garbage +5 (keep last 5 generations) would align better with how developers actually think about cleanup -- you want a safety buffer, not a binary choice.
In the meantime, for anyone who needs finer control, this two-step approach works:
# Delete old generations but keep the last N
nix-env --delete-generations +5
# Then run GC (only collects what's now unreachable)
nix-store --gc
The bigger picture is that Nix store is often just one of many developer caches eating disk space. On a typical macOS dev machine, you might also have 10-20GB in Docker images, 5-10GB in Xcode DerivedData, plus npm/cargo/pip caches. For anyone trying to audit everything at once, I built ClearDisk -- it's a free open-source macOS menu bar app that gives you a breakdown of all developer caches including the Nix store. Helps you see the full picture before deciding what to clean.