What is the history of #! Interpreter first line in scripts?

The #! sequence, commonly called the shebang, was introduced by Dennis Ritchie at Bell Laboratories in January 1980. It was added to the Unix kernel to allow scripts to be executed directly as commands, making them behave more like regular executable programs.

Origin and Purpose

Before the shebang, executing a script in early Unix required explicitly calling the interpreter (e.g., sh script.sh). The operating system’s exec() system call could only run compiled binaries, which started with specific “magic number” bytes that the kernel recognized as machine instructions.

Dennis Ritchie changed the system so that the kernel would check the first two bytes of a file. If the bytes were CPU instructions, it would execute the file as a binary program.

If the bytes were the ASCII characters #! (hexadecimal 0x23 0x21), the kernel would read the rest of the line to find the path to an interpreter program. The kernel would then run that interpreter, passing the script’s filename as an argument.

This mechanism brought several key benefits:

Uniformity: Scripts could be executed uniformly like any other command, rather than only being runnable from within a shell.

Clarity in monitoring: Tools like ps (process status) would show the script’s actual name and interpreter, rather than just sh, aiding system monitoring and accounting.

Flexibility: It allowed for the use of various interpreters (e.g., sh, csh, perl, python, bash) without ambiguity, making the system more flexible.

Portability: It specified the intended interpreter within the script itself, ensuring it ran with the correct environment regardless of the user’s default shell.

Leave a Reply

Your email address will not be published. Required fields are marked *