How to use the command nix-collect-garbage (with examples)
Nix-collect-garbage is a command in Nix that allows users to delete unused and unreachable nix store paths. This command is useful for managing disk space by removing store paths that are no longer needed.
Use case 1: Delete all store paths unused by current generations of each profile
Code:
sudo nix-collect-garbage --delete-old
Motivation: The motivation for using this example is to free up disk space by deleting all store paths that are no longer in use by the current generations of each profile. This is useful for cleaning up the system and removing unnecessary files.
Explanation:
sudo
: This command is run with root privileges to give it the necessary permissions to delete files.nix-collect-garbage
: The main command that allows deleting unused nix store paths.--delete-old
: This flag tells the command to delete all store paths that are not used by the current generations of each profile.
Example output:
deleted '/nix/store/xxxxxxx'
deleted '/nix/store/yyyyyyy'
...
Use case 2: Simulate the deletion of old store paths
Code:
sudo nix-collect-garbage --delete-old --dry-run
Motivation: The motivation for using this example is to simulate the deletion of old store paths without actually deleting them. This is useful for checking which store paths would be deleted before performing the actual deletion.
Explanation:
--dry-run
: This flag tells the command to simulate the deletion of old store paths without actually deleting them. It provides a preview of the files that would be deleted.
Example output:
would delete '/nix/store/xxxxxxx'
would delete '/nix/store/yyyyyyy'
...
Use case 3: Delete all store paths older than 30 days
Code:
sudo nix-collect-garbage --delete-older-than 30d
Motivation: The motivation for using this example is to delete all store paths that are older than 30 days. This is useful for cleaning up the system and removing outdated files.
Explanation:
--delete-older-than
: This flag tells the command to delete all store paths that are older than the specified time period.30d
: This argument specifies the time period. In this case, it means 30 days.
Example output:
deleted '/nix/store/xxxxxxx'
deleted '/nix/store/yyyyyyy'
...
Conclusion:
The nix-collect-garbage command in Nix is a powerful tool for managing disk space by deleting unused nix store paths. The provided use cases demonstrate how to delete unused store paths, simulate deletions, and delete old store paths based on a specified time period. By using this command, users can effectively clean up their system and reclaim valuable disk space.