Shebang
lastmod 2023-12-17created 2020-06-126 edits
A shebang is the character sequence consisting of the hash sign and exclamation mark (#!) at the very beginning of a script. It is also called sha-bang, hashbang, pound-bang, hash-pling, or crunchbang.
On Unix-like operating systems, a script with a shebang is run as a program, and the program loader parses the rest of the script's first line as an interpreter directive. That is, the specified interpreter program is run instead, and it is passed as an argument the path that was initially used when attempting to run the script. For example, if a script's path is path/to/script and it starts with the following line:
the program loader runs the program /bin/sh instead, passing path/to/script as the first argument.
The shebang line is usually ignored by the interpreter, because the "#" character is a comment marker in many scripting languages. Some language interpreters that do not use the hash mark to begin comments, such as Scheme, may ignore the shebang line for this purpose. Another solution is to rely on a preprocessor to remove or evaluate the shebang line before the rest of the script is passed to the compiler or interpreter. An example is InstantFPC, which allows programs written in Free Pascal to be run on various operating systems.
Another explanation of #!
- Stackoverflow: Why is '#!/usr/bin/env python' supposedly more correct than just '#!/usr/bin/python'?
- Chapter 2. Starting Off With a #!
The #! at the very beginning of a script tells the system which command interpreter the file's set of commands is intended for. The #! is a two-byte "magic number", a special marker that designates an executable shell script (man magic gives you more details on this fascinating topic). Immediately following the #! is a path name, the location of the program that interprets the commands in the script, whether it is a shell, a programming language, or a utility. This command interpreter then executes the commands in the script, starting at the top (the first line), ignoring comments.
In some environments, environment variables such as PATH are not applied, so the program cannot be found normally. For such cases, you can specify the program path as below.
#!/usr/bin/with-contenv bash
See s6##!/usr/bin/with-contenv bash for details.