Why does the "she-bang" begin with a #!
, like #!/bin/bash
? I have always accepted that this how it is done, but is there a reason behind it?
Why start with #
; isn't that usually a comment? Or is it the point that it should be comment?
Typically shebang refers to just the #!
(!
is typically called "bang", and it looks like "she" is a corruption of either "SHArp" or "haSH" for #
) -- the whole line is called a shebang line
It does intentionally start with a comment character for backwards-compatibility with things that don't know how to handle it; the !
is presumably just to distinguish it from a random comment starting the file, so a file that begins with # this is my script!
doesn't try to run the this is my script!
interpreter
!
is often used in other contexts to indicate a command to be executed. For example in vim
or other programs with their own command lines, bang is often the escape character that makes them run the command in a system shell instead of their internal interface.
To understand this you must realize that the first line of the script is actually read twice, by 2 different programs. The first time, the kernel opens the file and looks for that character sequence (#!
) on the first line. If it finds it, it runs the shell program that is indicated there, passing the file name as a parameter. (e.g. if the file /home/me/foo
starts with #!/bin/sh
, the kernel will run /bin/sh /home/me/foo
).
Next the shell (bin/sh
or whatever interpreter program was specified) reads the file. The shell does not know anything about shebang lines but it will still read the first line because it is just like any other line in the file... it reads them all. You don't want the shell to crash or alter its behavior in any way... the way to do that is to make it treat is as a comment and ignore it. Thus, the best character for a kernel instruction to start with would be the comment character.
It needs to be a comment because only this way it will also work to run a script like "interpretername scriptname". I do not know about the origin of the "!".
#!
(as much as dmr remembers…), including an explanation of why the#
(yes, the line had to be ignored by existing shells).