bash的标准位置是/bin,我怀疑在所有系统上都是如此。但是,如果您不喜欢这个版本的bash呢?例如,我想使用bash 4.2,但我的Mac上的bash是3.2.5。
我可以尝试在/bin中重新安装bash,但这可能是一个坏主意。如果我更新我的操作系统,它将被覆盖。
但是,我可以在/usr/local/bin/bash中安装bash,并将我的PATH设置为:
PATH="/usr/local/bin:/bin:/usr/bin:$HOME/bin"
现在,如果我指定bash,我就不会在/bin/bash中得到旧的、粗糙的代码,而是在/usr/local/bin中得到更新的、漂亮的代码。好了!
除了我的shell脚本有这个!因此,当我运行shell脚本时,我得到的是旧而糟糕的bash版本,它甚至没有关联数组。
使用/usr/bin/env bash将使用在我的PATH中找到的bash版本。如果我设置我的PATH,那么执行/usr/local/bin/bash,这就是我的脚本将使用的bash。
在bash中很少看到这种情况,但在Perl和Python中更常见:
Certain Unix/Linux releases which focus on stability are sometimes way behind with the release of these two scripting languages. Not long ago, RHEL's Perl was at 5.8.8 -- an eight year old version of Perl! If someone wanted to use more modern features, you had to install your own version.
Programs like Perlbrew and Pythonbrew allow you to install multiple versions of these languages. They depend upon scripts that manipulate your PATH to get the version you want. Hard coding the path means I can't run my script under brew.
It wasn't that long ago (okay, it was long ago) that Perl and Python were not standard packages included in most Unix systems. That meant you didn't know where these two programs were installed. Was it under /bin? /usr/bin? /opt/bin? Who knows? Using #! /usr/bin/env perl meant I didn't have to know.
为什么你不应该使用#!/usr/bin/env bash
When the path is hardcoded in the shebang, I have to run with that interpreter. Thus, #! /bin/bash forces me to use the default installed version of bash. Since bash features are very stable (try running a 2.x version of a Python script under Python 3.x) it's very unlikely that my particular BASH script will not work, and since my bash script is probably used by this system and other systems, using a non-standard version of bash may have undesired effects. It is very likely I want to make sure that the stable standard version of bash is used with my shell script. Thus, I probably want to hard code the path in my shebang.