8

I have a script I'd like to run... maybe something like this:

#!/usr/bin/env deno

console.log('hello world');

The shebang part is confusing. When I do it as above, with the filename dev, I get:

error: Found argument './dev' which wasn't expected, or isn't valid in this context

When I try to change the shebang to #!/usr/bin/env deno run

I get

/usr/bin/env: ‘deno run’: No such file or directory

Any thoughts on how to pull this off?

RandallB
  • 5,415
  • 6
  • 34
  • 47

2 Answers2

11

In order to pass command options to deno via env, you need the -S parameter for env.

For example, the following is the minimal shebang you should use for self-running a script with Deno.

#!/usr/bin/env -S deno run

Complex Example:

The following script/shebang will run Deno as silently as possible, with all permissions and will assume there is an import_map.json file next to the script file.

#!/usr/bin/env -S deno -q run --allow-all --import-map="${_}/../import_map.json"

// get file and directory name
const __filename = import.meta.url.replace("file://", "");
const __dirname = __filename.split("/").slice(0, -1).join("/");

The lines with __filename and __dirname will give you variables similar to Node's execution.


Script Installer

Deno also provides a convenient method for installing a script with it's permissions and dependencies in the configured distribution location.

See: Deno Manual - Script installer

Stand-Alone Executable

As of Deno 1.6, you can now build stand-alone executables from your script as well.

See: Deno Manual - Compiler - Compiling Executables

Martin Braun
  • 10,906
  • 9
  • 64
  • 105
dwmorrin
  • 2,704
  • 8
  • 17
  • Yes, I understand that. I'm trying to write shell scripts using deno / javascript. When I run that install, it just makes a shell script that invokes deno run. Is it possible to do that natively inside a shell script? – RandallB Jul 23 '20 at 09:30
  • 1
    @RandallB - Thanks for clarifying that you already knew about `deno install`. I updated my answer. – dwmorrin Jul 23 '20 at 10:25
  • What if I don't have the `-S` option? – Sean Nov 17 '20 at 01:35
  • @Sean then it won't work... to use `/usr/bin/env` with `deno run` as the command, you must have `-S` in between on the shebang line. I've updated the answer with a more complex example, as well as a minimal example. – Tracker1 Apr 12 '21 at 05:34
1

Deno 1.6.0

can compile to a standalone binary / executable file, no need for a custom Shebang:

$ deno compile --unstable main.js 
# or add custom output path
$ deno compile --unstable main.js -o /my/path/main
# both create ./main executable (e.g. on Linux)

# execute script directly
$ ./main 

More infos

ford04
  • 66,267
  • 20
  • 199
  • 171
  • 1
    When you provide Deno scripts that should be open-source (like helper scripts in a public repository), there is a need to use a custom Shebang, instead of compilation, definitely. – Martin Braun Jul 23 '21 at 23:52