What is the shebang?

The shebang (#!) is placed at the top of a script and is used to tell the kernel which interpreter to execute to read the script.

Syntax:

#!/path/to/interpreter [parameters (optional)]

The name shebang or hashbang comes from # (SHArp or HASH) and ! (bang).

Using a shebang like #!/usr/bin/echo will output just the filename (linux echo command), similarly #!/usr/bin/cat will output the contents of the file (linux cat command).

Note: Shebangs max out at 127 characters.

#!/usr/bin/env name

The /usr/bin/env command looks for and runs the first executable it finds in the user’s $PATH in a separate shell instance.

  • The #!/usr/bin/env shebang is used to increase portability of code.
  • It is also used in cases where the absolute path to the interpreter is unknown or may vary (such as when handling different versions of node with the Node Version Manager (nvm)).
#!/usr/bin/env node

Note: Arguments cannot be passed on to the interpreter when using #!/usr/bin/env.

Why #!?

The character sequence #!is encoded to the bytes 23 21, which is the magic number of an executable script.1

A magic number or file signature is a sequence of bytes at the beginning of a file that allows to identify the type of file. For example, a ZIP file has a file signature of 50 4B 03 04.2

Ref: