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

357 阅读1分钟

#! is called shebang which usage can be found in this article.

#!/usr/bin/env bash is to use the env program to search path to find a bash interpreter to execute the shell script. This behavior is useful when multiple versions of bash are installed. For example, my original default bash on my Mac is 3.2 but I installed version 5.1 via Homebrew. The version3.2 locate at /bin/bash while version 5.1 at /usr/local/bin/bash.

➜  ~ which -a bash
/usr/local/bin/bash
/bin/bash
➜  ~ /bin/bash --version
GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin20)
Copyright (C) 2007 Free Software Foundation, Inc.
➜  ~ /usr/local/bin/bash --version
GNU bash, version 5.1.12(1)-release (x86_64-apple-darwin20.6.0)
Copyright (C) 2020 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>

This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

I had changed my default bash to version 5.1 via this solution.

Now, open code editor to create a bash file which filename is set as First.sh

bash-5.1$ code First.sh

Add the following bash script to the file and save it.

#!/usr/bin/env bash 
echo $EPOCHSECONDS

Set execute permission to the file and run it directly.

bash-5.1$ chmod a+x First.sh
bash-5.1$ ./First.sh
1638788592

If we change the content of the file as below:

#!/bin/bash
echo $EPOCHSECONDS

Rerun the file, echo $EPOCHSECONDS statement will output nothing.

bash-5.1$ ./First.sh
(empty)

That's because $EPOCHSECONDS is a new variable released by GNU Bash 5 and /bin/bash on my computer is version 3.