Leon's Blogging

Coding blogging for hackers.

Ruby - 用 Ruby 來 Calling Shell Commands

| Comments

可以直接透過 ruby 來執行 commands 的指令。

  • Kernel#`, commonly called backticks

Returns the result of the shell command.

1
2
3
4
value = `echo 'hi'`
value = `#{cmd}`
value.class
#=> String 回傳結果
  • %x(cmd)

跟上面的 ` 是類似

Returns the result of the shell command, just like the backticks. 會以字串形式回傳結果

1
2
value = %x(echo 'hi')
value = %x[ #{cmd} ]
  • Kernel#system

指令執行結果成功與否,回傳的是布林值

Return: true if the command was found and ran successfully, false otherwise

1
2
3
4
wasGood = system("echo 'hi'")
wasGood = system(cmd)
wasGood.class
=> TrueClass 回傳有沒有成功
  • Kernel#exec

會中斷當前的 process

Return: none, the current process is replaced and never continues

1
2
exec("echo 'hi'")
exec(cmd) # Note: this will never be reached because of the line above

官方文件:

參考文件:

Comments