Node.js is very popular these days and I've been writing some scripts on it. Unfortunately, compatibility is a problem. Officially, the Node.js interpreter is supposed to be called node, but Debian and Ubuntu ship an executable called nodejs instead.I want portable scripts that Node.js can work with in as many situations as possible. Assuming the filename is foo.js, I really want the script to run in two ways:./foo.js runs the script if either node or nodejs is in $PATH.node foo.js also runs the script (assuming the interpreter is called node)Note: The answers by xavierm02 and myself are two variations of a polyglot script. I'm still interested in a pure shebang solution, if such exists.
Universal Node.js shebang?
scripting;compatibility;node.js
The best I have come up with is this two-line shebang that really is a polyglot (Bourne shell / Node.js) script:#!/bin/sh':' //; exec $(command -v nodejs || command -v node) $0 $@console.log('Hello world!');The first line is, obviously, a Bourne shell shebang. Node.js bypasses any shebang that it finds, so this is a valid javascript file as far as Node.js is concerned.The second line calls the shell no-op : with the argument // and then executes nodejs or node with the name of this file as parameter. command -v is used instead of which for portability. The command substitution syntax $(...) isn't strictly Bourne, so opt for backticks if you run this in the 1980s.Node.js just evaluates the string ':', which is like a no-op, and the rest of the line is parsed as a comment.The rest of the file is just plain old javascript. The subshell quits after the exec on second line is completed, so the rest of the file is never read by the shell.Thanks to xavierm02 for inspiration and all the commenters for additional information!