Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make global variable (or function) in nix file?

Tags:

nix

nixos

I want to declare variable dotfiles_dir so all other files can see and use it.

For example (not working)

In /etc/nixos/configuration.nix (it's root file, right?)

dotfiles_dir="/home/bjorn/.config/dotfiles";

import "${dotfiles_dir}/nixos/root/default.nix"

and use it also in ~/.config/nixpkgs/home.nix (with https://github.com/rycee/home-manager)

import "${dotfiles_dir}/nixos/home/default.nix"
like image 983
srghma Avatar asked Sep 06 '25 20:09

srghma


1 Answers

I want to declare variable dotfiles_dir so all other files can see and use it.

Sorry, but that's not possible. In Nix, there's no such thing as global variables. If there were, it would ruin it's ability to provide reproducible builds because then Nix expressions would have access to undeclared inputs.

/etc/nixos/configuration.nix is not place store global information, it's technically a NixOS module. But more importantly, it's a function.

However... there's a way to define a value in one place and use it where ever you need it. Something like this:

/etc/nixos/dotfiles-dir.nix

"/home/bjorn/.config/dotfiles"

~/.config/nixpkgs/home.nix

let 
  dotfiles_dir = import /etc/nixos/dotfiles-dir.nix;
  dotfiles = import (builtins.toPath "${dotfiles_dir}/nixos/home/default.nix");
in 
...

You could also get more fancy...

/etc/nixos/my-settings.nix

{
  dotfiles_dir = "/home/bjorn/.config/dotfiles";
  some_other_value = "whatever";
}

~/.config/nixpkgs/home.nix

let 
  dotfiles_dir = (import /etc/nixos/my-settings.nix).dotfiles_dir;
  dotfiles = import (builtins.toPath "${dotfiles_dir}/nixos/home/default.nix");
in 
...
like image 154
Emmanuel Rosa Avatar answered Sep 11 '25 00:09

Emmanuel Rosa