blackode

blackode

Writing a Command Line Application in Elixir (Intermediate level)

Hi and Hello Every Elixirian.

After Learning the Elixir basics, I struck then. I have no idea of how to put my Elixir Knowledge in practice. I want to move next level, but I am helpless. I am not that expert in elixir to work on innovative projects by myself that too alone. But I still managed with **iex **, but that does not last long. I Google and found the article on this topic , that really innovative for Intermediate level Elixir Programmer. So, I had thought of sharing and I added a bit of scent and explanation with clear steps.

Creating the Mix project

mix new commandline

After creating the project dive into the folders of project.

You will find the lib folder which holds the application code base and mix.exs file which is holding the application or project meta data like dependencies, creator, links, etc…

Now run mix to compile your app the first time after changing the directory to app root path.

Escript

Elixir uses escript to build an executable file that runs as normal script . Its only dependency is Erlang installed on your machine. Elixir is not necessary, since escript embedds Elixir into the compiled app. At first we need to set the main_module in mix.exsby extending the existing function:

escript: [main_module: Commandline.CLI] add this line in the project definition

def project do
  [app: :commandline,
  version: "0.1.0",
  elixir: "~> 1.3",
  escript: [main_module: Commandline.CLI],  # You have to add this extraline
  deps: deps]
end

Creating main_module

This main_module will act as the entry point for the command line application. This main_module should contain one main/1 function. Lets create the Commandline.CLI module with main/1 function.

Go to the lib directory and create new directory commandline and new file cli.ex with main/defintion

Now open cli.ex file and edit as follows.

defmodule Commandline.CLI do  #do not forget the namespace here
  def main(args) do
    {opts,_,_}= OptionParser.parse(args,switches: [file: :string],aliases: [f: :file])
    IO.inspect opts #here I just inspect the options to stdout
  end
end

args holds the command line arguments you will pass while executing the file.

OptionsParser.parse This parse the command line arguments and returns the tuple containing three values where we’re only interested in the first one. The second element holds remaining arguments and the last one invalid options. opts is a Keyword list containing all options converted to atoms with their associated value..

To explain this I will take one example.

Suppose you need to pass the filename as an option you can do that as follows .

Consider the commandline is executable file here

./commandline --file "blackode.txt" here --file is switch. You can pass as many you want. Here you can access that filename as opts[:file] which returns the string

./commandline -f "blackode.txt" here -f we have created aliases for file so we can access this as opts[:file] too as well.

Both approaches are very common for passing the data through the command line.

Building and Execution

To build the application you have to be in root path of the application and run the following command.

mix escript.build

This creates the executable file with name commandline

Run the Executable file with an argument

./commandline --file filename

or

./commandline --file=filename

If the file name contains the space wrap name inside the double quotes as “file name”

or

./commandline -f filename

The main function of the module takes all arguments, parses them and outputs a string to stdout

The yellow marked file is our executable file

Hope this helps :tada:

Most Liked

jwarlander

jwarlander

Once you have your project up on Hex / GitHub / any random Git repo, you can build & install it very easily if you’re on Elixir 1.4+:

mix escript.install git https://path/to/git/repo
mix escript.install git https://path/to/git/repo branch git_branch
mix escript.install git https://path/to/git/repo tag git_tag
mix escript.install git https://path/to/git/repo ref git_ref
mix escript.install github user/project
mix escript.install github user/project branch git_branch
mix escript.install github user/project tag git_tag
mix escript.install github user/project ref git_ref
mix escript.install hex hex_package
mix escript.install hex hex_package 1.2.3

If you’ve pre-built the escript and published it to a local web server, like Artifactory or something, you can also install it from there:

mix escript.install https://example.com/my_escript

For more details, see the documentation:

https://hexdocs.pm/mix/1.4/Mix.Tasks.Escript.Install.html

OvermindDL1

OvermindDL1

I think this makes sense as a wiki as well. Done.

Eiji

Eiji

I think that’s good topic to wiki - ping @AstonJ

blackode

blackode

Thank you :bouquet:

Where Next?

Popular in Wikis Top

Eiji
At start some definitions: HTTPS (is a protocol for secure communication over a computer network which is widely used on the Internet) -...
New
yurko
Here are few pieces of (common) Linux knowledge that we use for reasonably small one server apps. We use Ubuntu but this should work for ...
New
axelson
Preamble This Wiki is intended to be a community-maintained (see the Contribution Guidelines if interested) resource of common “gotchas” ...
New
georgeguimaraes
Hi people, since the new year is coming, I’d like to plan my travels for events in 2017. So, what events (Elixir or FP related) that you...
New
Rich_Morin
I’d like to start a discussion of data serialization formats, in the context of Elixir. The rest of this note is a combination of persona...
New
anildigital
Here is list of plugins for different editors Sublime Text 3 — Elixir.tmbundle - https://github.com/elixir-editors/elixir-tmbundle/#co...
New
AstonJ
Wonder if we can compile a list of learning resources, blog posts, talks, threads etc to help those who are just learning about Contexts....
New
blackode
This is a wiki - anyone at Trust Level 1 or higher can help keep it updated. Elixir Pocket Syntax Uncommon Logical stuff of Elixir modul...
New
BartOtten
A wiki for Doom Emacs Doom is a configuration framework for GNU Emacs. It focuses on performance and customizability. It can be a founda...
New
TunkShif
This post is an instruction guide to help you setup your Neovim for Elixir development from scratch. It includes general information on h...
273 38985 115
New

Other popular topics Top

chrismccord
Phoenix 1.4.0 released Phoenix 1.4 is out! This release ships with exciting new features, most notably with HTTP2 support, improved deve...
688 30048 115
New
dotdotdotPaul
Okay, I'm having a heck of a time trying to figure out how to best handle the validation of belongs_to associations in Ecto. I'm sure I'...
New
grych
Hi folks, Few months ago I have announced the proof-of-concept of the library to manipulate the browsers DOM objects directly from Elixi...
639 49522 488
New
KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 35421 110
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
fireproofsocks
I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Conside...
New
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers' Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
TunkShif
This post is an instruction guide to help you setup your Neovim for Elixir development from scratch. It includes general information on h...
273 38985 115
New
AstonJ
by Lance Halvorsen Elixir and Phoenix are generating tremendous excitement as an unbeatable platform for building modern web application...
460 27162 124
New

We're in Beta

About us Mission Statement