Nested #! only supported on Linux

I have a ruby script which require a few gems to be installed in order to run.

For this reason I am using bundlerEnv to prepare the ruby environment and then call patchShebangs after install, so that my script calls the wrapped ruby interpreter which sets up the necessary gem related environment variables.

The problem is that my script’s shebang (#!) now points to another script, which is not supported on macOS, and it appears only Linux supports nested #!.

My solution has been to call the wrapped ruby via /usr/bin/env, so after patchShebangs I run the following in my nix expression’s buildCommand:

sed -e "1 s/^#!/#!\/usr\/bin\/env /" -i -- $out/bin/«script_name»

This is a kludge and I would like to know if there is a better solution?

If there is no other solution to my problem, I would propose updating the patchShebangs shell function to check if the new interpreter is itself a script, and in that case, prefix it with /usr/bin/env.

Would a patch for this change be welcomed?

Definitely some changes on this are needed, but I think there may be issues with using /usr/bin/env everywhere too. There was some discussion here:

Part of the problem is that /usr/bin/env is actually not available in sandboxed builds. Probably fixing that is necessary first: