3
votes

Quick 1 liner: How does one start an OTP application and pass command-line args to it?

I wanted be able to start an OTP application in a generic "UNIX" way, being able to pass command-line arguments parsed by getopts. So, I have an erlang escript which uses the getopt library to handle parsing of command-line arguments.

shino's answer got me on the right path:

  1. I have my escript do the getopts parsing
  2. The escript then loads the application description into memory with application:load/1
  3. I then use application:set_env/3 to store the CLI args
  4. Now, launch the application with application:start/2
  5. Once the application launches, the arguments can be accessed via application:get_env/2
2

2 Answers

2
votes

You can use init:get_plain_arguments/0 function in order to access command line (extra) arguments.

Example:

$ erl -sname example -extra extra args here
Erlang R15B (erts-5.9) [source] [64-bit] [smp:2:2] [async-threads:0] [kernel-poll:false]

Eshell V5.9  (abort with ^G)
(example@localhost)1> init:get_plain_arguments().
["extra","args","here"]

init:get_plain_argumets/0 returns arguments after -extra option as a list of strings. Option sname is just for explanation, which does not appear in init:get_plain_argumets/0.

For more detail, see document on init module http://www.erlang.org/doc/man/init.html .

2
votes

You can also override application environment settings on the command line:

erl -myapp foo bar ...

This will set application.get_env(myapp, foo) to "bar", overriding any app.config setting.