27

Some scripting languages (such as Python or Bash) use # for comments.

#!/usr/bin/env python
print 'hello, world'

I can run the script:

python script.py

Or

./script.py

Is it possible to make JavaScript support shebang?

Dan Dascalescu
  • 127,343
  • 44
  • 300
  • 387
kev
  • 146,428
  • 41
  • 264
  • 265
  • See also what is [the appropriate shebang for Node.js](https://stackoverflow.com/questions/20638520/appropriate-hashbang-for-node-js-scripts/28646724). – Dan Dascalescu May 03 '19 at 04:20

1 Answers1

47

Yes, you can simply use #!/usr/bin/env node (or whatever the name of your JavaScript interpreter is, it works fine with js (spidermonkey), too).

[me@hades:~]> cat > test.js
#!/usr/bin/env node
console.log('hi');
[me@hades:~]> chmod +x test.js
[me@hades:~]> ./test.js
hi

Most likely both interpreters test if the first line begins with #! and in this case it is skipped.

ThiefMaster
  • 298,938
  • 77
  • 579
  • 623
  • 4
    Does node ignore the first line? `#` is not a comment in javascript. – kev May 22 '12 at 05:40
  • 7
    Yes, if it's a shebang line. Otherwise it would be a SyntaxError. – ThiefMaster May 22 '12 at 05:41
  • 2
    YUI Compressor throws an error saying that this (the #!) is an illegal character. Further, my IDE (Eclipse) shows this as an error as well. What gives? Is it valid or not? – Chris Jordan Aug 10 '15 at 19:13