Skip to content

Basic Usage

Albert Álef edited this page Feb 3, 2026 · 2 revisions

Basic Usage

RubyShell provides multiple ways to execute shell commands as Ruby methods.

Block Form

The most common way to use RubyShell:

sh do
  pwd
  ls("-la")
  mkdir("new_folder")
end

Inside the block, any method call that doesn't exist in Ruby becomes a shell command.

Method Chaining

Call commands directly on sh:

sh.git("status")
sh.docker("ps", all: true)
sh.ls("-la", "/var/log")

Direct Command Form

Pass the command name as a symbol:

sh(:git, "status", s: true)
sh(:ls, "-la")

Module Extension

Extend a class or module to use commands directly:

class MyScript
  extend RubyShell::Executor

  def self.run
    git("status")
    rake("spec")
  end
end

Return Values

Commands return a StringResult object that behaves like a String:

result = sh.ls
puts result           # Print output
result.lines.each     # Iterate lines
result.include?("x")  # String methods work

Directory Scoping with cd

The cd command accepts a block and returns to the original directory when done:

sh do
  cd "/var/log" do
    puts tail("-n", "10", "syslog")
  end
  # Automatically back to original directory
end

Next: Arguments and Options

Clone this wiki locally