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 calledShebang
. Here’s a note about it.
Shebang
- Shebang is
#!
, and if it exists, it must be the first two characters of the first line of the file. - 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.
- 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
—Usesh
, i.e., Bourne shell or other compatible shells to execute the script#!/bin/csh
—Usecsh
, i.e., C shell to execute#!/usr/bin/env node
—Usenode
, 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.