Understanding Shebang

· 1 min read · 249 Words · -Views -Comments

I often see shell files with #!/bin/sh at the beginning. Sometimes they can run without it, and I wasn’t sure what it was for. It wasn’t until recently when writing Alfred Workflow that I learned this is called Shebang. Here’s a note about it.

https://static.1991421.cn/2024/2024-04-02-235754.jpeg

Shebang

  1. Shebang is #!, and if it exists, it must be the first two characters of the first line of the file.
  2. When a file contains Shebang, the program loader of Unix-like operating systems analyzes the content after Shebang, uses it as interpreter instructions, calls that instruction, and passes the file path containing Shebang as a parameter to the interpreter.
  3. A file can exist without a Shebang line, but it cannot be executed directly. However, if you call the file using the interpreter directly, it can run.

Examples

  • #!/bin/sh—Use sh, i.e., Bourne shell or other compatible shells to execute the script
  • #!/bin/csh—Use csh, i.e., C shell to execute
  • #!/usr/bin/env node—Use node, i.e., Node.js to execute. Using env here avoids needing to use the absolute path to node.

Node Example

#!/usr/bin/env node
console.log(
  JSON.stringify({
    response: process.env.ruleContent,
    footer: process.env.ruleName
  })
);

As shown above, it can be executed directly in the terminal. If you delete the first line, direct execution will report an error unless you use node xxx to execute it.

Authors
Developer, digital product enthusiast, tinkerer, sharer, open source lover