Bash – the difference in these two bash environments

bashexecutableshebangshell-script

I notice that with bash scripts, some people use a different
shebang to the one that I'm used to putting at the top of my own.

Can someone simplify the difference between these two? I use the #!/bin/bash one all the time.

#!/bin/bash
#!/usr/bin/env bash

Best Answer

The #!/usr/bin/env bash results in the script using whatever bash is found first in $PATH.

While it is common for bash to be located at /bin/bash. There are cases where it is not (different operating systems). Another potential use is when there are multiple bash shells installed (newer version at an alternate location like /usr/local/bin/bash).

Doing #!/usr/bin/env bash just takes advantage of a behavior of the env utility.
The env utility is normally used for manipulating the environment when calling a program (for example; env -i someprog to wipe the environment clean). However by providing no arguments other than the program to execute, it results in executing the specified program as found in $PATH.


Note that there are both advantages and disadvantages to doing this.

The advantages are as mentioned earlier, in that it makes the script portable if bash is installed in a different location, or if /bin/bash is too old to support things the script is trying to do.

The disadvantage is that you can get unpredictable behavior. Since you're at the mercy of the user's $PATH, it can result in the script being run with a version of bash that has different behavior than what the script expects.

Related Question