Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make a single-file script with Elixir, without excess output?

Tags:

elixir

I would like to do something that seems like it should be simple, namely make a script that outputs a greeting message and nothing else. This script is so simple that it shouldn't require more than one file. Here's what I tried:

[ ~/elixir ] cat hello.exs
#!/usr/bin/env iex
IO.puts "Hello world!"
:init.stop

[ ~/elixir ] ./hello.exs
Erlang/OTP 17 [erts-6.3] [source] [64-bit] [smp:4:4] [async-threads:10] [hipe] [kernel-poll:false] [dtrace]

Hello world!
Interactive Elixir (1.0.2) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> [ ~/elixir ]

This is pretty close to the desired result, but I'm looking for something like a --quiet or --silent flag to suppress the Erlang and Elixir startup messages. Adding the -S flag to iex doesn't help:

[ ~/elixir ] cat hello.exs
#!/usr/bin/env iex -S
IO.puts "Hello world!"
:init.stop

[ ~/elixir ] ./hello.exs
Erlang/OTP 17 [erts-6.3] [source] [64-bit] [smp:4:4] [async-threads:10] [hipe] [kernel-poll:false] [dtrace]

-S : Could not find executable ./hello.exs

I know it's possible (http://goo.gl/MtFTQF) to use mix to create a project for this, but it seems like overkill. All I want to do right now is make a simple hello script.

like image 612
ijt Avatar asked Feb 25 '15 22:02

ijt


People also ask

Can you make elixir write a program for itself?

Can you make Elixir write a program for itself? Put this code into a file called script.ex with File.write/2: IO.puts "This file was generated from Elixir" and then make it run by running elixir that-file.ex . Figure out what happens if you try to delete a file that doesn't exist with File.rm/1.

How does elixir write fixed contents to a file?

iex> File.write ( "fixed-haiku.txt", fixed_contents) :ok Elixir dutifully takes the file path and the fixed contents and puts them into a file called fixed-haiku.txt. Well, we assume so. All that we know about this operation is that Elixir thought it went OK, as indicated by the atom that it returned: :ok .

What kind of files can I read in Elixir?

Certain files may contain data that we can use in our Elixir programs. Elixir can read any file you throw at it. In this chapter, just for simplicity, we're going to stick to a single file format: text files. A text file is just a file with a bunch of words in it. You probably have a file like that on your computer right now.

What do I need for file manipulation in Elixir?

That’s a simple introduction to file manipulation with Elixir, all you need is the File, and the input-output IO modules. Thank you so much for your time, I really appreciate it.


1 Answers

You should use the elixir executable to run Elixir files (#!/usr/bin/env elixir). iex will execute the file and start the Interactive Shell.

like image 189
José Valim Avatar answered Jan 04 '23 06:01

José Valim