In this article, we are going to see that what is the difference between #!/usr/bin/bash and #!/usr/bin/env bash
What is #!?
This is called the shebang character sequence consisting of the character’s number sign and an exclamation mark at the beginning of the script. It is also called sharp-exclamation, sha-bang, hashbang, pound-bang, or hash-piling. this character sequence tells the OS to invoke the specified shell to execute the commands that follow in the script.
Using #!/usr/bin/bash
This is a shebang line used in script files to set bash, present in the “/bin” directory, as the default shell to execute the commands in the file. It defines the absolute path /usr/bin/bash to the Bash shell.
We can find where your bash is located in the system by which command:
$ which bash /usr/bin/bash
using #!/usr/bin/bash is recommended when users want to accurately point to an interpreter’s absolute path. it also offers high security and is open to passing additional parameters.
#!/usr/bin/bash -r
Using #!/usr/bin/env bash
It is also a shebang line used in script files to execute commands with a bash shell. the difference is it uses the env command to display the environment variable present in the system, then executes commands with a defined interpreter. The env command works by instructing the system to look for specifies interpreters through the $PATH variable and use the first occurrence found.
$ which bash /usr/bin/env
Also, you can identify all the current environment variables defined by the shell by using the command env.
$ env
$ env | grep PATH
Table of Difference Between #!/usr/bin/bash and #!/usr/bin/env bash
From the above, we can see $PATH contains symlinks to /bin and other directories also.
Sr.No | #!/usr/bin/bash | #!/usr/bin/env bash |
---|---|---|
1 | It offers more security | It offers more Portability |
2 | It can support extra parameters passing after the declaration of an interpreter. | Automatically searches for the interpreter and chooses the first occurrence. |
3 | More specifically, since we are declaring the exact path to an interpreter. | Cannot support extra parameter passing because the system reads them as a single command. |
4 | Not offers modification to the environment. | Offer the possibility to modify the environment of the invoked command |
5 | Runs the only bash executable that is located in #!/usr/bin/bash. | It makes sure that if the script interpreter is accessible on the path then it will be found and gets executed. |