Skip to content

Executable scripts ​

A hashbang (the first line starting with #!) tells the operating system which command should run a file. With a tsx hashbang, you can execute a TypeScript file as ./file.ts instead of typing a separate tsx command.

This page assumes a Unix-like environment, such as macOS or Linux, with /usr/bin/env supporting -S to split hashbang arguments. Native Windows shells do not use this execution mechanism. To run a script without a hashbang or executable permissions, use npx tsx ./file.ts from a project with tsx installed.

Project scripts ​

Use a project-local installation when the script belongs to a project. This lets the project declare its tsx version rather than relying on a global installation.

First, install tsx in the project. Save one of these alternatives as file.ts, choosing the package manager your project uses:

file.ts

ts
#!/usr/bin/env -S npx tsx

console.log('argv:', process.argv.slice(2))
ts
#!/usr/bin/env -S pnpm exec tsx

console.log('argv:', process.argv.slice(2))
ts
#!/usr/bin/env -S yarn tsx

console.log('argv:', process.argv.slice(2))

The selected package manager must be on your PATH. Run the script from the project directory so the package manager can find the local tsx installation. Install dependencies first: npx can offer to download tsx when it is not available locally.

Make the file executable:

sh
chmod +x ./file.ts

Run it with arguments:

sh
./file.ts hello world

It prints:

text
argv: [ 'hello', 'world' ]

Global scripts ​

Use a global installation for scripts that you want to run outside a particular project. The script then depends on the tsx version available in the user's environment.

Install tsx globally and ensure tsx is on your PATH, then save this file in a directory of your choice:

file.ts

ts
#!/usr/bin/env tsx

console.log('argv:', process.argv.slice(2))

From that directory, make it executable and run it:

sh
chmod +x ./file.ts
./file.ts hello world

It prints:

text
argv: [ 'hello', 'world' ]

This hashbang finds tsx through PATH; it does not select a project's local installation.

Troubleshooting ​

  • Permission denied when running ./file.ts: From the directory containing the file, run chmod +x ./file.ts before trying again.
  • The package manager or tsx is not found: The command named in the hashbang must be on PATH. For a project script, install the project's dependencies and use its package manager. For a global script, check the global installation setup.
  • A project script cannot find the local installation: Run it from the project directory, not just from any directory containing the script. The package manager uses the working directory to find project dependencies.