Why can I not execute a new version of nix with `nix shell`?

I really tried my best to find out what’s going wrong here, but I just don’t get it.

Basically, I wanted to install nix 2.16.1 to try it out, but it doesn’t seem to work:

$ nix shell nixpkgs#nixVersion.2_16
$ nix --version
nix (Nix) 2.15.1
$ which nix
/nix/var/nix/profiles/default/bin/nix
$ nix run nixpkgs#xonsh -- -c 'print("\n".join($(echo $PATH).split(":")))'
/nix/store/2rrfpkq6cr8ppip9szl0z1qfdlskdinq-python3-3.10.12/bin
/nix/store/4xmsm8r1kfnlhx9ly5hsq0af4j0qgmvz-xonsh-0.14.0/bin
/nix/store/09dnrzkz6f9swzyd4xqfwhfx8fzfxgm7-python3.10-pygments-2.14.0/bin
/nix/store/f75w9c9zdbylkh5dakvfxf4f1xdhzznx-python3.10-docutils-0.19/bin
/Users/felix/Documents/Apps/google-cloud-sdk/bin
/Users/felix/.nix-profile/bin
/Users/felix/.nix-profile/bin
/nix/var/nix/profiles/default/bin
/nix/store/s3x3y9av1m1d63gl02ccigvv1c2kn3ym-nix-2.16.1-man/bin
/nix/store/2x4vxqiyc5hbvca755b80f1rba3zsdzj-nix-2.16.1/bin
/Users/felix/Documents/Apps/google-cloud-sdk/bin
/Users/felix/.cargo/bin
/Users/felix/.nix-profile/bin
/nix/var/nix/profiles/default/bin
[...]

Haha, ok, after agonizing for half an hour, now I got it. I implemented a workaround for this issue a while ago, which is to source nix in my home .zshrc:

[ -e "/nix/var/nix/profiles/default/etc/profile.d/nix-daemon.sh" ] && source "/nix/var/nix/profiles/default/etc/profile.d/nix-daemon.sh"
[ -e "$HOME/.nix-profile/etc/profile.d/nix.sh" ] && source "$HOME/.nix-profile/etc/profile.d/nix.sh"

nix shell, as it starts a new instance of zsh, causes this to be sourced again, but it is added to $PATH after nix shell’s additions, and so those take precedence.

My fix was check whether nix is available first:

[[ ! $(command -v nix) && -e "/nix/var/nix/profiles/default/etc/profile.d/nix-daemon.sh" ]] && source "/nix/var/nix/profiles/default/etc/profile.d/nix-daemon.sh"                                                
[[ ! $(command -v nix) && -e "$HOME/.nix-profile/etc/profile.d/nix.sh" ]] && source "$HOME/.nix-profile/etc/profile.d/nix.sh"

That fixed my $PATH completely.

I’ll leave this here for posterity.

1 Like

Maybe mark the post as solved too :slight_smile:

1 Like