Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What effect does /usr/bin/env have?

Tags:

shell

shebang

What's the difference between #! /usr/bin/env ruby and #! ruby?

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

like image 845
John Bachir Avatar asked Mar 11 '23 05:03

John Bachir


1 Answers

#! ruby

...is 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.

like image 85
Charles Duffy Avatar answered Mar 15 '23 11:03

Charles Duffy