threads / discuss / 305

Why /usr/bin/env in scripts

Subject: Why /usr/bin/env in scripts

## tl;dr

3 messages between Apr 25, 2005 and Apr 25, 2005.

replies: 2people: 3as markdown or json

Philip Pokorny· Apr 25, 2005, 07:38 UTC · lore
I notice that the first line of the pasky shell scripts is
#!/usr/bin/env bash
rather than what I'm more familiar with:
#!/bin/bash

I see that env can be used to alter the environment before running a program, but that doesn't seem to be happening here.

In fact, on my system /usr/bin/env is a link to /bin/env...
So what am I missing?  Is this a portability aid?

Thanks, :v)

David Greaves· Apr 25, 2005, 09:42 UTC · re: Philip Pokorny · lore

Re: Why /usr/bin/env in scripts

Philip Pokorny wrote:
> I notice that the first line of the pasky shell scripts is
> 
> #!/usr/bin/env bash
> So what am I missing?  Is this a portability aid?
man env:

The first remaining argument specifies the program name to invoke; it is searched for according to the `PATH' environment variable. Any remaining arguments are passed as arguments to that program.

It's a trick to do a PATH search for a script interpreter rather than hard coding the path. Now all we have to do is make sure every distro on the planet has /usr/bin/env - and they do.

David
David A. Wheeler· Apr 25, 2005, 17:45 UTC · re: Philip Pokorny · lore

Re: Why /usr/bin/env in scripts

Philip Pokorny wrote:
Show 7 quoted lines
> I notice that the first line of the pasky shell scripts is
>
> #!/usr/bin/env bash
>
> rather than what I'm more familiar with:
>
> #!/bin/bash
...
> So what am I missing?  Is this a portability aid?

Correct. Bash gets installed in different places on different systems, e.g., on OpenBSD bash is NOT in /bin or /usr/bin, but in /usr/local/bin. Invoking "/bin/sh" on OpenBSD will _NOT_ get you bash, but a pdksh variant that doesn't implement the bash capabilities some scripts require. Using env this way an old trick; I don't know who originally came up with it.

Technically, even this isn't 100% portable. Leading "#!" (shebang) isn't implemented by a very few old systems (it's not in the Single User Spec, though it was introduced between v7 and v8 of Unix). Also, you can find one or two really obscure systems where env isn't in /usr/bin (OpenServer 5 and a few really old Linux distributions). But env is ONLY in /usr/bin for the *BSDs. This version runs on 99.999% of the Linux/Unix systems, and takes essentially zero effort to implement; "more portable" solutions are so much more work that few people bother if they're writing shell scripts.

--- David A. Wheeler

← back to recent threads