0

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?

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
Vorac
  • 3,077

1 Answers1

2

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.

user2233709
  • 1,669
  • 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? – Vorac Nov 19 '17 at 11:03
  • Searching the PATH is not exactly a shell feature; it is a libc feature. That’s only a guess, but /usr/bin/env might be required by the POSIX standard. – user2233709 Nov 19 '17 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). – David Favor Nov 19 '17 at 13:01
  • @DavidFavor It does not matter that it’s a comment, it matters that it is a special kernel feature. – user2233709 Nov 19 '17 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… – user2233709 Nov 19 '17 at 14:23