Running an Elixir File as a Script

Elixir is able to run “scripts” or files that are compiled into memory (not on disk) and executed. This is helpful when experimenting with larger Elixir code snippets. This is also helpful if you just want to occasionally run one-off scripts to perform some work and exit.

File: my_test_script.exs

defmodule MyTestScript do

  def say_hi do
    IO.puts "Hello!"
  end

end

MyTestScript.say_hi

To execute the file, from a command-line in the same directory as the file, you can run:

$ elixir my_test_script.exs 
Hello!

The output “Hello!” is displayed in the terminal.

What Just Happened?

This does the following things:

  1. A BEAM instance is started
  2. The file my_test_script.exs is loaded and compiled in memory. The interpreted symbols are loaded into the VM.
  3. The code after the module, (i.e.MyTestScript.say_hi) is interpreted and run.
  4. After completing execution, the BEAM instance is shutdown.

File Extension .exs?

The file extension used on the file is .exs. A normal Elixir file that is compiled ends in .ex. The “s” denotes it is a script and should be interpreted at runtime and not compiled.

Thinking Tip

Files ending in .exs are also used for writing your test files, project configuration files, database migrations and custom scripts. After all, you don’t want your unit test code to be compiled into your deployed project!

Downsides

There are several downsides with building any significant amount of source code using .exs script files.

  • They aren’t as performant. They must be “compiled” again each time they are run.
  • As a project grows, you want to break it out into multiple files for code organization and your own sanity. When running as a script, it is difficult to load and include those other files. However, you can do it. I just don’t recommend it.
  • If your code starts some concurrent tasks, the new processes will spawn and the BEAM promptly shuts down because it completed all the statements you gave it to execute. You can tell the runtime to keep it going using elixir --no-halt my_test_script.exs. To exit, hit CTRL+C, CTRL+C (yup, 2 times) to kill the running BEAM instance.

Mix Project Alternative

A better approach that’s easy to do and will grow with you as you experiment is creating a new mix project.

Leave a Comment

You must be logged in to post a comment.