Search code examples
nix

How to ignore a missing file in the imports?


i have this in my nix config:

imports = [
    # Include the results of the hardware scan.
    ./hardware-configuration.nix
    /home/dev/user.nix
];

When i do now nixos-install, it tells me that user.nix doesnt exist (which is true, since the file is supplied much later).

Is there a way to only import that file when it exists or ignore that error?


Solution

  • You can use the builtins.fileExists function.

    imports = [
      ./hardware-configuration.nix
    ] ++ lib.optional (builtins.fileExists /home/dev/user.nix) [ /home/dev/user.nix ];
    

    This uses lib.optional to conditionally include the /home/dev/user.nix file in the imports list if it exists. If the file doesn't exist, lib.optional returns an empty list, so nothing is added to imports.