Building CLI scripts with Elixir

Elixir can make an elegant language for CLI scripts (if relatively slow script startup times due to BEAM startup are not a concern), but there’s a few quirks to be aware of.

Standalone exs scripts

It’s possible to create files with a .exs extension, which can be run as small ad-hoc scripts. These don’t need to be part of a Mix project and can be run with elixir script.exs.

Scripts invoked like this don’t have access to application code or other project dependencies, though as of Elixir 1.12.0 it’s possible to use Mix.install/2 when outside of a Mix project to install and start dependencies.

Mix run

When inside of a Mix project, mix run can be used to start the current application dependencies, the application itself, and then run the given script.

The advantage of this approach is that you have access to project dependencies and all application code.

Escripts

Lastly, it’s possible to create a single, largely self-contained executable per Mix project, called an escript.

This will compile the entire project and bundle the Elixir runtime into the resulting script, so the only runtime requirement that remains is Erlang being present on the system.

The :escript key must be defined in mix.exs for this, as explained in mix escript.build.

References