--- title: "Open An IEx Shell From An Elixir Script" blurb: "We can run an Elixir script with either the `elixir` or the `iex` 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 `elixir`, instead of `iex`, to run our script?" ... I recently had occasion to want to start an IEx session from an Elixir script. Here's how I was able to do it. ## Method 1 Here's a quick test script:
`run.exs`
```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.