Bash vs Dash – POSIX Compliance When sh is a Symlink

bashdashshellshell-script

From Difference between bash and sh:

ABck to the question: If you have /bin/sh as a link to bash, then bash will not behave the same when called as /bin/sh as it does when called as /bin/bash. When called as sh, it will limit itself to mostly POSIX-compliance plus a limited set of extensions.

Does it mean that whenever I come across a shell script in Linux with a shebang to sh: #!/bin/sh, even if on that distro, bin/sh is a symlink to another shell, like dash or bash, it should be 100% compatible with the bourne shell, since it limit itself to a limited set of extension? So I could execute them in FreeBSD? Is there are exception to that? Or I should be safe to assume that it will work?

So if on a distro, bin/sh is a symlink to bin/bash, and a script use #!/bin/sh and the script contain bashism, it will not run, since bash will like be in sh mode?

Best Answer

No, if /bin/sh is a symlink to bash bash enters just posix mode - from man bash:

When invoked as sh, bash enters posix mode after the startup files are read.

If you now search for posix mode at the bash manpage you'll see that some shell builtins like time or source behave differently. That is all. bashishms like writing function before declaring a function or using source instead of . still will work but the commands may behave differently.

So if /bin/sh is a symlink to /bin/bash all typical bashishms still work.

For a pretty extensive list of differences in the Posix mode have a look at the bash reference manual.

Related Question