Friday, 10 May 2013

What is Shebang or Hashbang in Unix/Linux?

In a script if the first line consists of characters number sign and exclamation sign (i.e #!) then such a sequence is know as Shebang or a Hashbang.

This hashbang takes arguments. The first argument is always the path to the interpreter that will be used to interpret the script code to follow.

Suppose you are writing a shell script then the 1st line of your script would be something like #! /bin/sh . Code which will follow this will be interpreted by your shell(whatever you have usually this is Bourne shell).

Another point to note that hashbang begins with a # character which is interpreted as comment in most of the scripts. So the corresponding interpreter will ignore this line.

Syntax

Syntax is very simple#! interprter [optional arg]

Note this must be the 1st line of your script.

The interpreter must usually be an absolute path to a program that should be used to interpret rest of the script code.

Example

Some usage examples are -

#!/bin/sh — Execute the file using sh, the Bourne shell, or a compatible shell

#!/bin/csh -f — Execute the file using csh, the C shell, or a compatible shell, and suppress the execution of the user’s .cshrc file on startup

#!/usr/bin/perl -T — Execute using Perl with the option for taint checks

#!/usr/bin/php — Execute the file using the PHP command line interpreter

#!/usr/bin/python -O — Execute using Python with optimizations to code

#!/usr/bin/ruby — Execute using Ruby

Purpose of a Hashbang

Purpose is fairly straight forward. Lets say you have a perl script(GetIP.pl) and perl module is installed at /usr/bin/install/perl . Every time you wish to execute this file(from any directory you are in) you will need to give the absolute path where perl module is located to run the script /usr/bin/install/perl GetIP.pl but using hashbang all you need to do is GetIP.pl . It will execute the script using perl module directly.

What happens behind the scene(Magic number)?

The Shebang is actually a human readable instance of magic number in executable file. The magic byte string being 0x23 0x21 , the two character encoding in ASCII. The magic number is detected by "exec" family of functions which determine whether the image file is a script or an executable binary. The presence of shebang will result in execution of specific executable, usually an interpreter for the script's language.