LoginSignup
12
12

More than 5 years have passed since last update.

Ruby でシェルのコマンドを実行する

Last updated at Posted at 2014-04-21

みなさんは Ruby でシェルのコマンドを実行する際はどうしていますか?

私はだいたいは Kernel.#system メソッドや FileUtils モジュールを利用しますが、
今回 Shell という標準ライブラリを見つけたのでそれを活用してみました。

require 'shell'

Shell.def_system_command("ls")
Shell.alias_command("ls1", "ls", "-1")
Shell.def_system_command("sort")

my_shell = Shell.new
my_shell.cd("hidamari")

# ls -1 を実行
puts my_shell.ls1
# [出力結果]
# hiro.txt
# miyako.txt
# sae.txt
# yuno.txt

contents = nil
my_shell.transact do
  # ls -1 | sort -r を実行
  contents = (ls1 | sort("-r")).map.with_index(1) do |file, i|
    filename = file.chomp
    # cat を実行
    "(#{i}) #{filename.rjust(10)}: #{cat(filename)}"
  end
end

puts contents
# [出力結果]
# (1)   yuno.txt: Yuno (CV: Kana Asumi)
# (2)    sae.txt: Sae (CV: Ryoko Shintani)
# (3) miyako.txt: Miyako (CV: Kaori Mizuhashi)
# (4)   hiro.txt: Hiro (CV: Yuko Goto)

軽く使ってみた上で、ポイントとしては

  • メソッドが用意されていないコマンドは Shell.def_system_command で登録する。
  • Shell.alias_command でエイリアスも定義できる。
  • Shell#transact のブロック中では shell オブジェクトが self となるので、より直感的にコマンドを実行できる。
  • パイプ | が使える。

といったところでしょうか。

まあ system メソッドを使ったり、そもそも Ruby じゃなくて bash で書いたりしてもいいのでしょうが、
こういう方法もあるよということで。 ✌( 'ω' )✌

12
12
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
12
12