To pass extra parameters to the function inside a shell.nix file, you can define the function to accept multiple parameters, each with a default value. This allows for more customizable and flexible usage. Here are a few ways to achieve this:
Example 1: Simple Function with Extra Parameters
Let's assume you have a shell.nix file where you want to accept additional parameters.
{ pkgs ? import <nixpkgs> {},
myVar ? "default_value" }:
pkgs.mkShell {
buildInputs = [ pkgs.hello pkgs.gcc ];
shellHook = ''
echo "The value of myVar is: ${myVar}"
'';
}
Calling the Function with Extra Parameters
To call this shell.nix and pass extra parameters, you can use the nix-shell command-line option -E to override the defaults:
nix-shell --argstr myVar "new_value"
Alternatively, you can create another file to override the parameters:
shell-with-args.nix:
(import ./shell.nix {
myVar = "new_value";
})
Then, you can simply run:
nix-shell shell-with-args.nix
Example 2: Using args Record for Multiple Parameters
If you have many parameters, it is often cleaner to use a record to group them.
shell.nix:
{ pkgs ? import <nixpkgs> {},
args ? {
myVar = "default_value";
anotherVar = "another_default";
}
}:
pkgs.mkShell {
buildInputs = [ pkgs.hello pkgs.gcc ];
shellHook = ''
echo "The value of myVar is: ${args.myVar}"
echo "The value of anotherVar is: ${args.anotherVar}"
'';
}
Passing the Record
shell-with-args.nix:
(import ./shell.nix {
args = {
myVar = "overridden_value";
anotherVar = "overridden_another_value";
};
})
Then run:
nix-shell shell-with-args.nix
Example 3: Passing Nested Arguments
You can even pass arguments in a nested structure if needed.
shell.nix:
{ pkgs ? import <nixpkgs> {},
args ? {
myVar = "default_value";
nestedArgs = {
innerVar = "default_inner";
};
}
}:
pkgs.mkShell {
buildInputs = [ pkgs.hello pkgs.gcc ];
shellHook = ''
echo "The value of myVar is: ${args.myVar}"
echo "The value of innerVar is: ${args.nestedArgs.innerVar}"
'';
}
Passing Nested Arguments
shell-with-args.nix:
(import ./shell.nix {
args = {
myVar = "overridden_value";
nestedArgs = {
innerVar = "overridden_inner";
};
};
})
Then run:
nix-shell shell-with-args.nix
Summary
- Using Default Parameters: You provide default values for parameters in your
shell.nix file and override them when calling the function.
- Using Records: Group multiple parameters in a record for cleaner and more organized code, especially when dealing with many parameters.
- Passing Nested Structures: You can create complex, nested parameter structures if needed.
This approach allows for flexible and clean parameter management in your shell.nix files.