Shebang

From Linux Shell Scripting Tutorial - A Beginner's handbook
Jump to: navigation, search
← Hello, World! TutorialHomeShell Comments →

The #! syntax used in scripts to indicate an interpreter for execution under UNIX / Linux operating systems. Most Linux shell and perl / python script starts with the following line:

#!/bin/bash

OR

#!/usr/bin/perl

OR

#!/usr/bin/python

OR lisp script : [1]

 #!/usr/local/bin/sbcl --script
     (write-line "Hello, World!")


Starting a Script With #!

  1. It is called a shebang or a "bang" line.
  2. It is nothing but the absolute path to the Bash interpreter.
  3. It consists of a number sign and an exclamation point character (#!), followed by the full path to the interpreter such as /bin/bash.
  4. All scripts under Linux execute using the interpreter specified on a first line[2].
  5. Almost all bash scripts often begin with #!/bin/bash (assuming that Bash has been installed in /bin)
  6. This ensures that Bash will be used to interpret the script, even if it is executed under another shell[3].
  7. The shebang was introduced by Dennis Ritchie between Version 7 Unix and 8 at Bell Laboratories. It was then also added to the BSD line at Berkeley [4].

Ignoring An Interpreter Line (shebang)

  • If you do not specify an interpreter line, the default is usually the /bin/sh. But, it is recommended that you set #!/bin/bash line.

/bin/sh

For a system boot script, use /bin/sh:

#!/bin/sh

sh is the standard command interpreter for the system. The current version of sh is in the process of being changed to conform with the POSIX 1003.2 and 1003.2a specifications for the shell.

An example of /bin/sh script

  • /etc/init.d/policykit
#! /bin/sh
### BEGIN INIT INFO
# Provides:          policykit
# Required-Start:    $local_fs
# Required-Stop:     $local_fs
# Default-Start:     2 3 4 5
# Default-Stop:
# Short-Description: Create PolicyKit runtime directories
# Description:       Create directories which PolicyKit needs at runtime,
#                    such as /var/run/PolicyKit
### END INIT INFO
 
# Author: Martin Pitt <martin.pitt@ubuntu.com>
 
case "$1" in
  start)
        mkdir -p /var/run/PolicyKit
        chown root:polkituser /var/run/PolicyKit
        chmod 770 /var/run/PolicyKit
	;;
  stop|restart|force-reload)
	;;
  *)
	echo "Usage: $SCRIPTNAME {start|stop|restart|force-reload}" >&2
	exit 3
	;;
esac
 
:

For a typical script use the #!/bin/bash shell.

External links

References

  1. SBCL - Shebang Scripts
  2. Howto Make Script More Portable With #!/usr/bin/env As a Shebang FAQ by nixCraft.
  3. Bash man page and the official documentation.
  4. extracts from 4.0BSD /usr/src/sys/newsys/sys1.c.
← Hello, World! TutorialHomeShell Comments →