E1.獲取Elixir/Erlang版本資訊
阿新 • • 發佈:2021-01-25
### E1.獲取Elixir/Erlang版本資訊
#### 獲取Elixir版本
直接在shel中開啟`iex` (interactive shell),就可以查到具體的版本資訊:
```elixir
iex
Erlang/OTP 22 [erts-10.6] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:1] [hipe] [dtrace]
Interactive Elixir (1.9.0) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)>
```
使用符合GUN選項標準`--version`或`-v`,比如在寫Shell指令碼時可以用來判斷版本。
```elixir
iex --version
Erlang/OTP 22 [erts-10.6] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:1] [hipe] [dtrace]
IEx 1.9.0 (compiled with Erlang/OTP 22)
iex -v
Erlang/OTP 22 [erts-10.6] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:1] [hipe] [dtrace]
IEx 1.9.0 (compiled with Erlang/OTP 22)
```
在程式碼中獲取版本資訊:[System.version/0](https://hexdocs.pm/elixir/System.html#version/0)
```elixir
iex(1)> System.version
"1.9.0"
```
#### 獲取Erlang版本
Erlang無法使用`erl --version`命令,只能通過命令列選項[eval與noshell](http://erlang.org/doc/man/erl.html)引數求值來實現。
```elixir
erl -eval 'erlang:display(erlang:system_info(otp_release)), halt().' -noshell
```
- `eval` :對Erlang表示式求值。
- `noshell`: 不啟動shell,就像上面的elixir --version一樣。
- `halt()`退出當前執行時
由於`:erlang.system_info(:opt_release)`只能拿到一個大版本號:比如**22**:
```elixir
iex(1)> :erlang.system_info(:otp_release)
'22'
```
如果想要更詳細的版本資訊可以使用:
```elixir
erl -noshell -eval \
> '{ok, Version} = file:read_file(filename:join([code:root_dir(), "releases", erlang:system_info(otp_release), "OTP_VERSION"])), io:fwrite(Version), halt().'
22.2
```
上面的程式碼來源於[Erlang官方文件](http://erlang.org/doc/system_principles/versions.html)。
多個表示式寫成一行使用逗號隔開,顯得不那麼容易理解,還可以把多個表示式分開寫:
```elixir
erl -noshell -eval \
'{ok, Version} = file:read_file(filename:join([code:root_dir(), "releases", erlang:system_info(otp_release), "OTP_VERSION"])), io:fwrite(Version).'\
-eval 'halt().'
22.2
```
或用`-s`引數:
```elixir
erl -noshell -eval \
> '{ok, Version} = file:read_file(filename:join([code:root_dir(), "releases", erlang:system_info(otp_release), "OTP_VERSION"])), io:fwrite(Version).'\
> -s erlang halt
22.2
```
PS:上面的`OTP_VERSION`檔案是從R17後才有的。
從R17開始,OTP的大版本代表的是一組特定版本的應用(Applications),這一組合通過了愛立信官方OTP團隊的測試,但是個人也可以不升級大版本,只升級其中的某個特定應用的版本,這樣的組合的相容性沒有經過官方驗證/測試,需要自己充分測試,所以沒有經過充分的測試,別隻單獨升級個別應用,最佳實踐是保持和官方大版本一致的應用版本。
> It is therefore **always preferred to use OTP applications from one single OTP version**.
想要得到那些應用在本版本做了變更,可以檢視檢視[otp_versions.table](https://github.com/erlang/otp/blob/master/otp_versions.table),它羅列了每個版本具體的改動情況,每一行代表一個版本,比如:
```elixir
OTP-22.1.1 : compiler-7.4.6 erts-10.5.1 snmp-5.4.1 # asn1-5.0.9 common_test-1.18 crypto-4.6 debugger-4.2.7...
```
- `OTP-22.1.1`: OTP版本。
- `compiler-7.4.6 erts-10.5.1 snmp-5.4.1:`發生了變更的應用。
- `#`後面的應用為未發生變更。
![](https://images.cnblogs.com/cnblogs_com/zhongwencool/1590234/o_210125091029%E6%89%AB%E7%A0%81_%E6%90%9C%E7%B4%A2%E8%81%94%E5%90%88%E4%BC%A0%E6%92%AD%E6%A0%B7%E5%BC%8F-%E6%A0%87%E5%87%86%E8%89%B2%E7%89%