iex can be used for interactively experimenting with elixir. If this experimentation becomes elaborate, it can be useful to store the commands in a file. This post covers working with files that store elixir code snippets. Attention is paid to code that depends on mix project modules.

Software Versions

$ date -u "+%Y-%m-%d %H:%M:%S +0000"
2016-03-14 17:08:09 +0000
$ uname -vm
FreeBSD 11.0-CURRENT #0 r296709: Sat Mar 12 21:18:38 JST 2016 root@mirage.sennue.com:/usr/obj/usr/src/sys/MIRAGE_KERNEL amd64
$ elixir --version
Erlang/OTP 18 [erts-7.2.1] [source] [64-bit] [async-threads:10] [hipe] [kernel-poll:false]

Elixir 1.2.3

Instructions

A single line can be run from the command line.

elixir -e 'IO.puts("Hello, mix run!")' # general elixir code
mix run -e 'IO.puts("Hello, mix run!")' # project specific code

Something more elaborate probably wants to live in a file.

snippets/hello.exs

#!/usr/bin/env elixir

IO.puts "Hello, Elixir!"

The above file be run from the command line as is, but it will not have acces to modules in the mix project.

chmod +x snippets/hello.exs
./snippets/hello.exs

Run the file with mix run if any mix project modules are referenced.

mix run snippets/hello.exs

Note that c or Code.load_file can be used to load the file in iex.

c "snippets/hello.exs"
Code.load_file "snippets/hello.exs"

Code.load_file can be used to load one file from another file. This is fragile if using relative paths.

snippets/indirect.exs

#!/usr/bin/env elixir

Code.load_file "snippets/hello.exs"

To run mix code snippets directly from the command line, add the following file to some place on your path. For example, $(which mix)-snippet.

mix-snippet

#!/bin/sh

mix run "$1"

Make mix-snippet executable.

chmod +x mix-snippet # use the actual path

The mix-snippet shebang can now be used.

snippets/hello-mix-snippet.exs

#!/usr/bin/env mix-snippet

IO.puts "Hello, mix-snippet!"

Code snippets that depend on the mix project can now be executed from the command line.

chmod +x snippets/mix-snippet-hello.exs
./snippets/mix-snippet-hello.exs

References: