Your First Elixir Script
Writing and running a standalone .exs script, and understanding how it differs from a compiled mix project.
2 min read
Elixir gives you two ways to run code: compiled projects managed by mix, and standalone scripts you run directly with the elixir command. For learning and quick experiments, scripts are the faster path — no project scaffolding required.
.ex vs .exs
Elixir source files come in two flavors:
.exfiles are meant to be compiled — typically part of a mix project, producing bytecode that's cached and loaded quickly..exsfiles are scripts — interpreted fresh every time, no compilation step, ideal for one-off code and tests.
For your first program, .exs is the right choice.
Writing the script
Create a file named hello.exs:
IO.puts("Hello from Elixir!")
name = "World"
IO.puts("Hello, #{name}!")
numbers = [1, 2, 3, 4, 5]
sum = Enum.sum(numbers)
IO.puts("The sum of #{inspect(numbers)} is #{sum}.")A few things worth noticing already, even before later lessons formalize them: IO.puts/1 prints a line to standard output, #{} interpolates a value into a string, and Enum.sum/1 is a function from Elixir's standard library that reduces a list to a single number.
Running it
elixir hello.exsHello from Elixir!
Hello, World!
The sum of [1, 2, 3, 4, 5] is 15.
No compile step, no build artifacts — the elixir command reads the file top to bottom and executes it directly.
Defining and using a module in a script
Even a quick script can define a module, which is how Elixir organizes related functions:
defmodule MathHelpers do
def square(n) do
n * n
end
def is_even?(n) do
rem(n, 2) == 0
end
end
IO.puts(MathHelpers.square(6))
IO.puts(MathHelpers.is_even?(6))36
true
Functions ending in ? are a naming convention (not a language rule) for functions that return a boolean — is_even?/1 reads naturally in an if later on, exactly the way Enum.empty?/1 or String.contains?/2 do in the standard library.
Passing arguments from the command line
Scripts can read arguments via System.argv/0:
# greet.exs
[name | _rest] = System.argv()
IO.puts("Hey there, #{name}!")elixir greet.exs Alice
# => Hey there, Alice!That [name | _rest] = System.argv() line is your first taste of pattern matching — destructuring a list into its first element and "everything else." The next section of this course covers exactly what's happening there and why it's one of Elixir's most useful features.
From here on, most lessons in this course will show snippets you can drop straight into a .exs file and run with elixir filename.exs to see the output for yourself — doing that as you go is the fastest way to build real intuition for the language.
Test what you just learned
4 quick questions. Get all of them right to unlock the next lesson.
You can take the quiz without an account — logging in just lets your result count toward your progress.