The difference between “#! /usr/bin/env bash” and “#! /usr/bin/bash”? [closed]

Tag: linux , bash , shell , unix , hashbang Author: georgejg Date: 2013-04-17

In the header of a bash script, what's the difference between those two statements ?

  1. #!/usr/bin/env bash

  2. #!/usr/bin/bash

When I tried to see the env man page, I'm just get this definition:

 env - run a program in a modified environment

What does it mean ?

Best Answer

Running a command through /usr/bin/env has the benefit of looking for whatever the default version of the program is in your current environoment.

This way, you don't have to look for it in a specific place on the system, as those paths may be in different locations on different systems. As long as it's in your path, it will find it.

The downside is that since you aren't calling an explicit executable, it's got the potential for mistakes, and on multiuser systems security problems (if someone managed to get their executable called bash in your path, for example).

`#!/usr/bin/env bash` #lends you some flexibility on different systems
`#!/usr/bin/bash`     #gives you explicit control on a given system of what executable is called

In some situations, the first may be preferred (like running python scripts with multiple versions of python, without having to rework the executable line). But in situations where security is the focus, the latter would be preferred, as it limits code injection possibilities.

comments:

Sorry, but "*env*ironoment" looks very ugly.
@tarrsalah: And #! doesn't? What do you mean?
Another drawback is that you can't pass an additional argument to the interpreter.
Made a slight adjustment tarrsalah :)
@AlecBennett you can just use HTML ;)

Other Answer1

Using #!/usr/bin/env NAME makes the shell search for the first match of NAME in the $PATH environment variable. It can be useful if you aren't aware of the absolute path or don't want to search for it.

Other Answer2

Instead of explicitly defining the path to the interpreter as in /usr/bin/bash/, by using the env command, the interpreter is searched for and launched from wherever it is first found. This has both upsides and downsides

comments:

On most systems, they will be functionally the same, but it depends on the location of your bash and env executables. Not sure how this will affect environment variables, though.
"It is possible to specify the interpreter without using env, by giving the full path to the interpreter. A problem is that on different computer systems, the exact path may be different. By instead using env, the interpreter is searched for and located at the time the script is run. This makes the script more portable, but also increases the risk that the wrong interpreter is selected because it searches for a match in every directory on the executable search path. It also suffers from the same problem in that the path to the env binary may also be different on a per-machine basis."-Wikipedia