Which of the above forms is "better" for running bash, python etc. scripts? Why can't I just do #!$(which foo)
? Is it neccecery to specify full path to env
? I gather from this answer, that the path /usr/bin/env
is set in stone for all *nix-es, much more than /usr/bin/python3
for example. Is that so?
1 Answer
You can’t just write #!$(which foo)
because that line is interpreted by the kernel, which does not understand complex syntaxes like $()
.
The kernel does not search for the command in the PATH
environment variable. That’s why you have to specify the full path to the command.
The use of /usr/bin/env
is a clever hack used to search the command in the PATH
. Even if there is a /usr/bin/python3
program, you may for example have installed a more recent version of Python in a different path, for example in you home directory.
-
Ahaa, so
$()
is a shell feature. As well as searching the path, consequently I can't just write#!python3
. What about the cross-platform issue. Do we get/usr/bin/env
on MacOS? FreeBSD? QNX?– VoracNov 19, 2017 at 11:03 -
Searching the
PATH
is not exactly a shell feature; it is alibc
feature. That’s only a guess, but/usr/bin/env
might be required by the POSIX standard. Nov 19, 2017 at 11:13 -
You can't use #!$(which foo) because shell expansion does not occur for comments... as in #! (a comment)... This is by specific design. There is no "better" or "best" way to set your interpreter. I tend to use #!/usr/bin/env perl + #!/usr/bin/env ffmpeg, because I build these nightly, against latest source. So in general, you'll use /usr/bin/env when you have multiple copies of a program in your $PATH + you'd like to take the highest precedence version (one appearing first in your $PATH variable). Nov 19, 2017 at 13:01
-
@DavidFavor It does not matter that it’s a comment, it matters that it is a special kernel feature. Nov 19, 2017 at 13:08
-
@MarkPlotnick Are you sure it is a feature of the shell? I just gave it a try, and could also run that shell script through /usr/bin/env… Nov 19, 2017 at 14:23