如何保存 IEx 历史记录?

How do I save IEx history?

使用 IEx(Elixir 的 REPL),我希望能够保存我的命令历史记录。

例如:

我可以打开一个新的 IEx 会话并执行命令。执行命令后,我可以按向上箭头并预填充我的最后一个命令。关闭 IEx 并重新打开后,我想访问我最后的命令。

有办法吗?

为Erlang/OTP20

这是内置的(来自https://hexdocs.pm/iex/IEx.html#module-shell-history

From Erlang/OTP 20, it is possible to get shell history by passing some flags that enable it in the VM. This can be done on a per-need basis when starting IEx:

iex --erl "-kernel shell_history enabled"

If you would rather enable it on your system as a whole, you can use the ERL_AFLAGS environment variable and make sure that it is set accordingly on your terminal/shell configuration.

On Linux [and macOS]:

export ERL_AFLAGS="-kernel shell_history enabled"

On Windows:

set ERL_AFLAGS "-kernel shell_history enabled"

要显示历史文件所在的位置,运行 来自 erl 的以下代码(Mac OS 显示的示例值):

1> filename:basedir(user_cache, "erlang-history")
"/Users/your.username/Library/Caches/erlang-history"

要将文件设置到不同的位置,请使用 shell_history_path /path/to/history-file option from the erlang docs (compatible with Elixir/iex):

export ERL_AFLAGS="-kernel shell_history_path '\"$HOME/.erlang-history\"'"

Erlang/OTP19 岁及以下

尝试使用 https://github.com/ferd/erlang-history

> git clone https://github.com/ferd/erlang-history.git
> cd erlang-history
> sudo make install    # may not need sudo depending on installation

我正在使用 oh-my-zsh,所以我设置了 vim ~/.zshrc:

# Enable history in IEX through Erlang(OTP)
export ERL_AFLAGS="-kernel shell_history enabled"

然后 source ~/.zshrc 现在始终加载。谢谢@loeschg。

我不知道事情是否在某些时候发生了变化,但我发现上面的方法不起作用。查看 iex 的手册页后,我注意到它需要

export ELIXIR_ERL_OPTIONS="-kernel shell_history enabled"

(注意额外的 ELIXIR)。也许最初的解决方案是有说服力的与 erl 相关(我发现它适用于此),但 iex 添加了限定词?由于最初的问题 for iex,所以认为应该更新它。

对于 docker compose,您需要创建一个卷来保存历史记录,并通过 -kernel shell_history_path 告诉 Erlang 它在哪里。路径必须是 Erlang 术语,因此请确保它是 '"tripple quoted"':

version: '3'

services:
  elixir:
    environment:
      ERL_AFLAGS: -kernel shell_history enabled -kernel shell_history_path '"/somewhere/sensible"'
    volumes:
      - type: volume
        source: shell_history
        target: /somewhere/sensible

volumes:
  shell_history: