Can't run `nix-shell` in scripts: `rm` not found

When running scripts using the nix-shell shebang or ones that at some point use nix-shell -p foo --run foo, I get a very odd error:

/nix/store/xfhkjnpqjwlf6hlk1ysmq3aaq80f3bjj-stdenv-linux/setup:20: command not found: shopt
_nix_shell_clean_tmpdir: command not found: rm

This error happens when running this code:

#!/usr/bin/env nix-shell
#!nix-shell -i bash -p bash

echo hello

or this code:

#!/usr/bin/env bash

nix-shell -p bash --run "echo hello"

or this code:

#! /usr/bin/env nix-shell
#! nix-shell -i python3 -p python3

print("hello")

If anyone has an idea of what might be going on here, I would love to know. Thanks for reading.

Not sure there’s enough context here to help you. This works, for example:

$ nix-shell -p bash --run "echo hello"
this path will be fetched (0.06 MiB download, 0.31 MiB unpacked):
  /nix/store/zzj7lxlhadcd6zws8gxs6ci5bxxjji10-bash-5.2-p21-dev
copying path '/nix/store/zzj7lxlhadcd6zws8gxs6ci5bxxjji10-bash-5.2-p21-dev' from 'https://cache.nixos.org'...
hello

do you know exactly which version of nixpkgs you are running?

/nix/store/xfhkjnpqjwlf6hlk1ysmq3aaq80f3bjj-stdenv-linux/setup:20: command not found: shopt is interesting, as shopt should be a bash built-in.

I’m on nixpkgs revision 57610d2f8f0937f39dbd72251e9614b1561942d8. And yes, I totally agree, this is one of the strangest errors I’ve seen. shopt is even in pure posix sh, which makes it even more confusing.

What’s weird is I can run this too, just not when it’s inside a script. If I put any of the above scripts in a file called ./test.sh and mark it as executable, it will error every time I run it.

I figured it out!

The problem was I had users.users.frostbyte.shell and users.defaultUserShell set to pkgs.zsh. Apparantly this makes nix-shell mad in some cases.

I would like to be able to use this feature with my default shell set to zsh, but I don’t know how to do that without causing this problem.

Does anyone else with zsh as their default shell have any input?