I basically want to create my own simple version of mkShell, so now I'm trying to understand how it would even be possible to execute some code before the shell actually pops up. I googled for a bit, and came up with this:
let pkgs = import <nixpkgs> {}; in
derivation {
name = "hello";
shellHook = ''
echo "hello world!"
'';
system = builtins.currentSystem;
builder = "${pkgs.bash}/bin/bash";
args = [ ./setup.sh ];
}
...where setup.sh contains echo "hello" > $out.
From nix-shell documentation:
If the derivation defines the variable shellHook, it will be run after $stdenv/setup has been sourced. Since this hook is not executed by regular Nix builds, it allows you to perform initialisation specific to nix-shell. For example, the derivation attribute
shellHook =
''
echo "Hello shell"
export SOME_API_TOKEN="$(cat ~/.config/some-app/api-token)"
'';
But that doesn't output anything, although if I replace derivation {} with pkgs.mkShell {}, then it does. How can I make this behaviour work without actually using pkgs.mkShell?
One means to avoid this issue is to use the newer replacement for
nix-shell,nix develop, to invoke a flake devShell. As a working example, after creating the followingflake.nix:...running
nix develop .#exampleDevShellprintsHello, worldto stdout.