Sunday, April 26, 2009

What is sharp-bang appear at first inside shell script

You might have seen that in many shell scripts the first line starts with a #! immediately following a path. The ! sign is called the exclamation mark and # sign is called the number sign/pound/hash. The another name of # sign is sharp and the ! sign is bang. The concatenation of # and ! is called the sha-bang (#!) or she-bang or sh-bang.

The sha-bang (#!) at the head of a script tells your system that this file is a set of commands to be fed to the command interpreter indicated. After #! there is path name which is the path to the program that interprets the commands in the script, whether it be a shell, a programming language, or a utility. This command interpreter then executes the commands in the script, starts at the top and ignore comments.

We know that in shell script any command starts with # is considered as comment. But if #! line in a shell script appear the first thing, then the command interpreter (sh or bash) sees and correctly interpret it but finally when the script executes the command interpreter consider the line as a comment. The line has already served its purpose - calling the command interpreter.

If, in fact, the script includes an extra #! line, then bash will interpret it as a comment.

The examples of commonly uses sha-bang are,
#!/bin/sh
#!/bin/bash -execute using bash shell.
#!/bin/ksh — Execute using korn shell.
#!/bin/zsh — Execute using Z shell.
#!/bin/sh — On Solaris this indicates Bourne shell. However on linux it points to bash shell.
#!/bin/csh — Execute using C shell.
#!/usr/bin/perl -Execute using perl.
#!/usr/bin/php — Execute using PHP.
#!/usr/bin/python — Execute using Python.
#!/usr/bin/ruby — Execute using Ruby.


The /bin/sh invokes the default shell interpreter which is /bin/bash on linux machine.

The /bin/bash explicitly invokes bash shell interpreter.

The path after sha-bang may also contain any utility path like,
#!/bin/sed -f
#!/usr/awk -f

While you scripting you can omit #! if the script consists only of a set of generic system commands, using no internal shell directives.

Note that the path given at the "sha-bang" must be correct, otherwise an error message -- usually "Command not found." will be the outcome of the script execution.

Related Documents
Introduction -What is kernel, shell, shell script.
Basic Steps to write a shell script
Variables in shell script
Output text with echo command

No comments:

Post a Comment