I recently wrote a patch for the GNU Coreutils version of env
to address this issue:
http://lists.gnu.org/archive/html/coreutils/2017-05/msg00018.html
If you have this, you can do:
#!/usr/bin/env :lang:--foo:bar
env
will split :lang:foo:--bar
into the fields lang
, foo
and --bar
. It will search PATH
for the interpreter lang
, and then invoke it with arguments --foo
, bar
, plus the path to the script and that script's arguments.
There is also a feature to pass the name of the script in the middle of the options. Suppose you want to run lang -f <thecriptname> other-arg
, followed by the remaining arguments. With this patched env
, it is done like this:
#!/usr/bin/env :lang:-f:{}:other-arg
The leftmost field which is equivalent to {}
is replaced with the first argument that follows, which, under hash bang invocation, is the script name. That argument is then removed.
Here, other-arg
could be something processed by lang
or perhaps something processed by the script.
To understand better, see the numerous echo
test cases in the patch.
I chose the :
character because it is an existing separator used in PATH
on POSIX systems. Since env
does PATH
searching, it's vanishingly unlikely to be used for a program whose name contains a colon. The {}
marker comes from the find
utility, which uses it to denote the insertion of a path into the -exec
command line.