In BlogPost, Elixir

Your First Elixir CLI Application With Escript

Functional programming is all the rage these days and Elixir can be a great way to dig into the concept. As I continued to explore Elixir, I wanted to understand how to write an Elixir CLI (command line interface) application.

elixir basics

Normally, I like to read a book about a new programming language and then try doing things with it. If you haven’t setup Elixir on your system, you can read this post for some help.

Step 1: Start an application

Step 2: Adding Choices

We’re going to write an application that prints out a list of choices and prompts you to pick one. It’s simple, but it will give you the idea.

Below is the program I wrote. We’ll walk through it in the next steps.

Example Program

Step 3: Add escript to mix.exs

Elixir uses escript to build your executable. This depends on Erlang, which you should have if you’ve already installed Elixir successfully.

Just add escript in your mix.exs file as shown below.

Step 4: The main function

You really need a main function to get the arguments passed in from the command line as shown in the example code. If you try to call it run or something else, you’ll get an error like the below.

Step 5: Build it

Next, you’ll need to build your CLI executable.

Step 6: Run the executable with args

It’s pretty straight forward. It passes the arguments form the command line to the private function parse_choices. We use the OptionParser library from Elixir to get the options hash.

This turns the command line argument you wrote into:

Once this gets passed as an argument into the output method, you then get a message depending on what you chose, so choose wisely!

Summary

As you can getting started writing your own Elixir CLI apps is pretty easy.

Recent Posts