Jan 30, 2015

Shebang, the Key to Portable Scripts


Although most Unix like operating systems these days have a port of the Bash shell, whether it is installed by default, where it is installed, and it's implementation does differ. For example, Linux installs Bash in /usr/bin where FreeBSD installs it in /usr/local/bin. When booting into Ubuntu, it may seem one is running Bash at first, but upon inspection one will notice that it is actually the Dash shell. The reason for changing to Dash can be found here.

To help improve compatibility across the growing number of OS' and distributions, a simple change can be applied. Enter the shebang! A shebang tells the OS what shell to use for the script by providing the absolute path to its executable, preceded by #! (shebang). As was mentioned above, the default path can vary depending on a few factors. There is a commonality among distributions which can eliminate this issue, and that is the env command. All this program does is look for the requested executable in all locations listed in $PATH. In other words, as long as bash is in one of the locations in $PATH, it will find it.  A shebang can also use env's absolute path instead of the shell's absolute path. All of the distributions I've looked at have env in the same location. So in conclusion, changing

#!/bin/bash

to

#!/usr/bin/env bash

 to your Bash shell script should solve most problems. An extremely simple solution to what may be a big headache otherwise.

No comments: