Scripts: shebang

A script without a #! (the so called shebang) in the very first line of the script is run by the “Bourne Shell”. To change the interpreter of the script you use the #!. Most often in scripts you will see that, it’s still #! /bin/sh though.

#!/bin/sh

echo "I am in the Bourne shell (maybe)"

That a Bourne compatible shell is reachable via /bin/sh is by convention, meaning that a system, where this is not the case, could be considered broken.

The Bourne Shell sh would be my ideal scripting environment, as it’s ubiquitous and can do everything that I need. There is just one snag. It’s very weak on string processing. In fact for most string manipulation tasks you need to rely on external tools like sed or tr. This makes the Bourne Shell just too slow. So in comes…

Bash

The bash has good string manipulation routines. It’s not the speediest kid on the block, but it gets the job done. And it’s everywhere.

/usr/bin/env bash

Unfortunately unlike sh, bash is not placed into /bin on every platform. So to get to the location of bash on the current system, without having to change the scripts for every install, one can use the useful env command, that searches the environment variable PATH for a command and then executes it.

#!/usr/bin/env bash

echo "Now I am in bash!"

Note

How dependable is the absolute path /usr/bin/env though ? Is it guaranteed by POSIX ? I don’t know. But so far this never failed me. #! /bin/bash though has and also #! /usr/bin/bash. So this is a step forward.