Shebang (Unix) - Portability

Portability

Shebangs must specify absolute paths to system executables; this can cause problems on systems that have a non-standard file system layout. Even when systems have fairly standard paths, it is quite possible for variants of the same operating system to have different locations for the desired interpreter. Python, for example, might be in /usr/bin/python, /usr/local/bin/python, or even something like /home/username/bin/python if installed by an ordinary user.

Because of this it is common to need to edit the shebang line after copying a script from one computer to another because the path that was coded into the script may not apply on a new machine, depending on the consistency in past convention of placement of the interpreter. For this reason and because POSIX does not standardize path names, POSIX does not standardize the feature.

Often, the program /usr/bin/env can be used to circumvent this limitation by introducing a level of indirection. #! is followed by /usr/bin/env, followed by the desired command without full path, as in this example:

#!/usr/bin/env sh

This mostly works because the path /usr/bin/env is commonly used for the env utility, and it invokes the first sh found in the user's $PATH, typically /bin/sh, if the user's path is correctly configured.

On a system with setuid script support this will reintroduce the race eliminated by the /dev/fd workaround described below. There are still some portability issues with OpenServer 5.0.6 and Unicos 9.0.2 which have only /bin/env and no /usr/bin/env.

Another portability problem is the interpretation of the command arguments. Some systems, including Linux, do not split up the arguments; for example, when running the script with the first line like,

#!/usr/bin/env python -c

That is, python -c will be passed as one argument to /usr/bin/env, rather than two arguments. Cygwin also behaves this way.

Another common problem is scripts containing a carriage return character immediately after the shebang, perhaps as a result of being edited on a system that uses DOS line breaks, such as Microsoft Windows. Some systems interpret the carriage return character as part of the interpreter command, resulting in an error message.

POSIX requires that sh is a shell capable of a syntax similar to the Bourne shell, although it does not require it to be located at /bin/sh; for example, some systems such as Solaris have the POSIX-compatible shell at /usr/xpg4/bin/sh. In many Linux systems and recent releases of Mac OS X, /bin/sh is a hard or symbolic link to /bin/bash, the Bourne Again shell.

Using syntax specific to Bash while maintaining a shebang pointing to the Bourne shell is not portable.

Read more about this topic:  Shebang (Unix)