Recommended reading:
- The UNIX FAQ: Why do some scripts start with #! … ?
- The #! magic, details about the shebang/hash-bang mechanism on various Unix flavours
- Wikipedia: Shebang
The unix kernel’s program loader is responsible for doing this. When exec()
is called, it asks the kernel to load the program from the file at its argument. It will then check the first 16 bits of the file to see what executable format it has. If it finds that these bits are #!
it will use the rest of the first line of the file to find which program it should launch, and it provides the name of the file it was trying to launch (the script) as the last argument to the interpreter program.
The interpreter then runs as normal, and treats the #!
as a comment line.