John Bachir John Bachir - 11 months ago 34
Bash Question

What effect does /usr/bin/env have?

What's the difference between

#! /usr/bin/env ruby
#! ruby

(I found many other questions discussing the difference between
#! /usr/bin/env ruby
#! /usr/bin/ruby
, but that's not my question.)

Answer Source
#! ruby not guaranteed to work on UNIXlike systems (and does not work on any I personally know of) at all; a valid shebang must have a fully qualified path. It may suffice to tell your editor which programming language you're using, but that doesn't mean that the kernel will successfully use it to select an interpreter with which to run a program.

The kernel's execve syscall doesn't do PATH lookups -- that's added by C-standard-library wrappers such as execlp and execvp, but parsing shebangs is done directly by the kernel, so your C-library nicities don't happen there.

#!/usr/bin/env ruby

...uses the PATH to look up the location of the ruby executable. Because the path to the env executable is fully specified, this is a valid shebang line (which #! ruby is not).

env has other purposes as well -- you can run, for instance, env -i someprog to run someprog with a completely empty environment, or env FOO=bar someprog to run someprog with the environment variable FOO set to the value bar (which FOO=bar someprog would also do if running through a shell, but the env approach also works with no shell involved).

However, the relevant use case in this context is forcing a PATH lookup.