How do I invoke deno from a shell script?

Viewed 1098

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?

2 Answers

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

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

Related