Shell – Shebang line for “run with $SHELL”

shebangshell-scriptzsh

I'm looking for what to put on my_zsh_script.sh's "shebang line" that would have the same effect, portably, as

$SHELL my_zsh_script.sh

IOW, I looking for the valid equivalent of

#!$SHELL

or

#!/usr/bin/env $SHELL    

(In some systems, my value for $SHELL is a version of zsh that, under some circumstances, differs from what #!/usr/bin/env zsh resolves to.)

I suppose that I can always arrange to have my_zsh_script.sh custom-built, with the right shebang line hard-coded in, for each host I may want to run it on. I'm hoping to avoid this scenario.

Best Answer

#!/bin/sh
my_script(){
    { cat; cat <&3; }>"$0"
} <<SHEBANG 3<<\SCRIPT
#!${SHELL}
SHEBANG
#now all the rest of your script

#goes in here

SCRIPT

my_script

most shells will put all of the contents of here-documents in secure temp files automatically. those that don't use pipes, and those buffers are usually more than enough to accomodate shell-script writes, but they're no sure thing, of course.

and functions are literal strings stored into the shell's memory. doing the above should only be required the one time, and afterwards your script will be interpreted by whatever was in $SHELL at the time you ran it.

Related Question