Frequently Asked Question

What is the shebang line and how does the kernel use it?

The first line of a script, beginning with #!, is called the shebang or hashbang. When the kernel is asked to execute a file, it reads the first two bytes; if it sees #! it treats the rest of the line as the path to an interpreter, and runs that interpreter with the script's path as an argument. So ./hello.sh becomes, in effect, /bin/bash ./hello.sh. This is how Linux supports scripts in any language at all (Python, Perl, awk, Ruby, Node) using the same mechanism.

The shebang line is parsed by the kernel itself (in fs/binfmt_script.c), not by the shell, which is why it must be the very first line and why the path must be absolute. Without a shebang, the kernel refuses to exec the file directly; the shell may fall back to running it as a sh script, but that fallback is fragile and you should not rely on it.

Video

Further reading and video