Sunday, August 04, 2013

Sha-bang

Scripts are text files which need to be executed as if they are executables. One way to do this is to execute the script by giving the name of the interpreter and the name of the script like this:
$ inter path/to/file
Here, inter should be replaced by the name of the interpreter. These would be the corresponding executables for the languages like ruby, perl, bash etc. But what if you don't want to expose which language the script is in?
The first thing that you need to do is provide executable permissions on the script. Once this is done, the script becomes eligible to be executed. In other words, it can be executed as follows:

$ path/to/file

A simplistic explanation of what happens is as follows1:
  1. The current process is forked and a copy of itself is created.
  2. The corresponding interpreter is exec'ed to execute the script with the right interpreter.

But how will the OS1 know the correct interpreter to use?

Enter Sha-bang!

Sha-bang is the term for the symbol #!. This has to be given as the first two characters in the script and should be followed by the path to the interpreter in the same line. Some examples are as follows:

#!/bin/bash

#!/usr/bin/ruby

The OS1 takes whatever is given after #! till the end of the line and does the exec using that.

It is important to remember that the rest of the line is totally taken and used. This means that you can have spaces before pass arguments to the interpreter. For example, -d can be passed to perl like this:

#!/usr/bin/perl -d

This would interpret the script as a Perl script and execute it in debug mode.

There is one catch in this method. What if the interpreter is installed in a different location from what is specified in the sha-bang?

The env command is used for this purpose. Here is the usage:

#!/usr/bin/env perl -d

This command finds the interpreter found in the environment variable $PATH and executes the command with the interpreter found.

1Please note that I am not trying to be technically correct. I am trying to explain things simply. For a proper understanding of this, I would suggest a book like Richard Stevens' Unix Network Programming.

Post a Comment