Explanation of the hash-bang (#!)

If you do any amount of scripting with any Unix-like operating system, you are probably familiar with the hash-bang (also known as the shebang).

The hash-bang, put at the start of a script, instructs the OS to use the program following the #! to interpret the script. For example, if you've got a Perl script and you set the permissions to executable, you won't automatically be able to just do:

$ ./myperlscript.pl

The OS doesn't know that it needs to use Perl to interpret the script and it will trip up.

So to remedy that, we put this at the beginning of the script:

#!/usr/bin/perl

I just found an ancient (but still useful) article about this and it's got some nice advanced uses of the hash-bang.

Once upon a time, Unix had only one shell, the Bourne shell, and when a script was written, the shell read the script and executed the commands. Then another shell appeared, and another. Each shell had its own syntax and some, like the C shell, were very different from the original. This meant that if a script took advantage of the features of one shell or another, it had to be run using that shell. Instead of typing:

doit

The user had to know to type:

/bin/ksh doit

or:

/bin/csh doit

To remedy this, a clever change was made to the Unix kernel -- now a script can be written beginning with a hash-bang (#!) combination on the first line, followed by a shell that executes the script. As an example, take a look at the following script, named doit...

The article was written in 1999, but it's still quite relevant for a lot of things today.

Read it here.

Avatar for peter Peter Upfold - http://peter.upfold.org.uk/

Peter Upfold is a technology enthusiast from the UK. Peter’s interest in Linux stems back to 2003, when curiosity got the better of him and he began using SUSE 9.0. Now he runs Linux Mint 9 on the desktop, runs a CentOS-based web server from home for his personal website and dabbles in all sorts of technology things across the Windows, Mac and open source worlds.

Home » Articles »

Discussion: Explanation of the hash-bang (#!)

Home » Articles » Explanation of the hash-bang (#!)