miti.sh/docs/2023-09-15-open-an-iex-shell-from-an-elixir-script.md
2025-05-11 15:06:23 -07:00

43 lines
1.5 KiB
Markdown

---
title: "Open An IEx Shell From An Elixir Script"
blurb: "We can run an Elixir script with either the <code>elixir</code> or the <code>iex</code> command. Both will execute the code, but the second command opens an interactive IEx shell afterward. What if, we won't know until runtime whether we want a shell or not? How can we start an IEx session even when we use <code>elixir</code>, instead of <code>iex</code>, to run our script?"
...
{
id: "open-an-iex-shell-from-an-elixir-script"
}
## Method 1
Here's a quick test script:
<p class="code-filename-label">`run.exs`</p>
```elixir
:shell.start_interactive({IEx, :start, []})
System.no_halt(true)
```
`System.no_halt(true)` is needed so that the interactive session doesn't die when the process running the script ends. You could also use the `elixir` command with the `--no-halt` option instead to achieve the same effect.
When we run this script with just `elixir` (instead of `iex`), we should still see an interactive IEx session start.
```bash
$ elixir run.exs
Erlang/OTP 26 [erts-14.1] [source] [64-bit] [smp:12:12] [ds:12:12:10] [async-threads:1] [jit:ns]
Interactive Elixir (1.15.6) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)>
```
## Method 2
While researching, I found another way that works, but it's even more obscure than the above method.
```elixir
:user_drv.start_shell(%{initial_shell: {IEx, :start, []}})
```
I can't find documentation for `user_drv`, I had to browse the [code](https://github.com/erlang/otp/blob/master/lib/kernel/src/user_drv.erl) directly.