LoginSignup
13
1

More than 1 year has passed since last update.

IExでもシェルコマンドを使えたらな〜と思うことはありませんか?

実はIEx.Helpersにシェルコマンド風の便利な関数がいくつか実装されています。

IEx Helpers

あくまでElixirコードですのでIEx.Helpers.cd/1のように引数を取る関数にはElixirの文字列を渡す必要があります。

IEx
iex> ls "lib"
toukon        toukon.ex

iex> ls lib
warning: variable "lib" does not exist and is being expanded to "lib()", please use parentheses to remove the ambiguity or change the variable name
  iex:3

** (CompileError) iex:3: undefined function lib/0 (there is no such import)
    (elixir 1.14.0) src/elixir_expand.erl:618: :elixir_expand.expand_arg/3
    (elixir 1.14.0) src/elixir_expand.erl:634: :elixir_expand.mapfold/5
    (elixir 1.14.0) src/elixir_expand.erl:848: :elixir_expand.expand_remote/8
    (elixir 1.14.0) src/elixir.erl:364: :elixir.quoted_to_erl/3
    (elixir 1.14.0) src/elixir.erl:274: :elixir.eval_forms/3
    (elixir 1.14.0) lib/module/parallel_checker.ex:100: Module.ParallelChecker.verify/1
    (iex 1.14.0) lib/iex/evaluator.ex:329: IEx.Evaluator.eval_and_inspect/3

ElixirのIoT開発プラットフォームであるNerves向けに開発されたtoolshedパッケージを活用すれば更にもっとたくさんのシェルコマンド風の関数が使えます。

Toolshed

  • cat/1
  • date/0
  • hostname/0
  • ifconfig/0
  • top/0
  • tree/1

toolshedパッケージをインストールして、use Toolshedにより関数をインポートします。

IEx
iex> Mix.install([{:toolshed, "~> 0.2"}])

iex> use Toolshed

いくつか使ってみます。

IEx
iex> date

iex> cat "mix.exs"

iex> tree "lib"

更にcmd/1を使えばどんな外部コマンドでも使えます。

IEx
iex> cmd "git branch"

:tada:

Systemモジュール

ElixirのSystemモジュールにもSystem.cmd/3System.shell/2があり、それらを使えばどんな外部コマンドでも使えます。ただし、戻り値に癖があるので直接使うのには若干不便です。

ご参考までに

13
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
1