Bash – Is it correct to use /bin/sh in the hashbang if the Bourne shell isn’t available in a distribution

bashshebangshellshell-scriptUbuntu

Generally, shell scripts contain the following comment at the first line of the script file: #!/bin/sh. According to the researches that I made, this is called "hash bang" and it is conventional comment. This comment informs Unix that this file is executed by the Bourne Shell under the directory /bin.

My question begins in that point. Up to now I have not seen this comment like #!/bin/bash. It is always #!/bin/sh. However, Ubuntu distributions do not have the Bourne Shell program. They have the Bourne Again Shell (bash).

In that point, is it correct to place the comment #!/bin/sh in shell scripts written in Ubuntu distributions?

Best Answer

#!/bin/sh should work on all Unix and Unix-like distributions. It is generally thought of as the most portable hashbang so long as your script is kept POSIX compliant. The /bin/sh shell is supposed to be a shell that implements the POSIX shell standard, regardless of what the actual shell is that masquerade as the /bin/sh shell.


#!/bin/sh is normally just a link now as the Bourne shell is no longer maintained. On many Unix systems /bin/sh will be a link to /bin/ksh or /bin/ash, on many RHEL based Linux systems it will be a link to /bin/bash, however on Ubuntu and many Debian based systems it is a link to /bin/dash. All shells, when invoked as sh, will enter POSIX compatibility mode.

The hashbang is an important placeholder though because it allows for much greater portability than other methods, so long as your script is strictly POSIX compliant (repeated to stress importance).

Note: When bash is invoked in POSIX mode it will still allow some non-POSIX things like [[, arrays, and more. Those things may fail on a non-bash system.