Skip to content

Examples

Albert Alef edited this page Feb 3, 2026 · 3 revisions

Examples

Real-world examples of RubyShell usage.

Git Workflow Automation

sh do
  changes = git("status", porcelain: true).lines

  if changes.any?
    puts "Stashing #{changes.count} changed files..."
    git("stash")
    git("pull", rebase: true)
    git("stash", "pop")
  else
    git("pull", rebase: true)
  end
end

Log Analysis

sh do
  cd "/var/log" do
    # Top 10 IPs by request count
    cat("nginx/access.log")
      .lines
      .map { |line| line.split.first }
      .tally
      .sort_by { |_, count| -count }
      .first(10)
      .each { |ip, count| puts "#{ip.ljust(15)} #{count} requests" }
  end
end

Docker Cleanup

sh do
  # Remove exited containers
  containers = docker("ps", a: true, format: "{{.ID}} {{.Status}}")
    .lines
    .select { |line| line.include?("Exited") }
    .map { |line| line.split.first }

  docker("rm", *containers) if containers.any?

  # Remove dangling images
  images = docker("images", f: "dangling=true", q: true).lines.map(&:strip)
  docker("rmi", *images) if images.any?

  puts docker("system", "df")
end

Batch File Processing

sh do
  find(".", name: "*.png")
    .lines
    .map(&:strip)
    .each do |png|
      webp = png.sub(/\.png$/, ".webp")

      begin
        cwebp("-q", "80", png, o: webp)
        rm(png)
        puts "Converted: #{png}"
      rescue RubyShell::CommandError => e
        puts "Failed: #{png} - #{e.message}"
      end
    end
end

System Health Check

sh do
  puts "=== Disk Usage ==="
  df("-h")
    .lines
    .drop(1)
    .each do |line|
      parts = line.split
      usage = parts[4].to_i
      mount = parts[5]
      puts "WARNING: #{mount} at #{usage}%" if usage > 80
    end

  puts "\n=== Top CPU Processes ==="
  ps("aux", sort: "-%cpu")
    .lines
    .drop(1)
    .first(5)
    .each { |proc| puts proc }
end

Deploy Script

#!/usr/bin/env ruby
require 'rubyshell'

DEPLOY_PATH = "/var/www/myapp"

sh do
  # Ensure clean state
  changes = git("status", porcelain: true).lines
  abort "Uncommitted changes!" if changes.any?

  # Run tests
  rake("spec")

  # Deploy
  cd DEPLOY_PATH do
    git("pull", "origin", "main")
    bundle("install", deployment: true)
    rake("db:migrate")
    systemctl("reload", "myapp")
  end

  puts "Deployed successfully!"

rescue RubyShell::CommandError => e
  puts "Deploy failed: #{e.message}"
  exit 1
end

Parsing Command Output

Use the _parse option to automatically parse command output into Ruby objects.

require "rubyshell/parsers/json"

sh do
  # Parse JSON output from kubectl
  pods = kubectl("get", "pods", o: "json", _parse: :json)
  pods[:items].each do |pod|
    puts "#{pod[:metadata][:name]} - #{pod[:status][:phase]}"
  end
end
require "rubyshell/parsers/yaml"

sh do
  # Parse YAML configuration
  config = cat("config.yml", _parse: :yaml)
  puts "Database: #{config[:database][:host]}"
end
require "rubyshell/parsers/csv"

sh do
  # Parse CSV data
  rows = cat("data.csv", _parse: :csv)
  rows.each do |row|
    puts row.join(" | ")
  end
end

Interactive Cleanup Script

sh do
  files = find(".", name: "*.tmp", mtime: "+30").lines.map(&:strip)

  if files.empty?
    puts "No old temp files found."
    exit
  end

  puts "Found #{files.count} temp files older than 30 days:"
  files.first(10).each { |f| puts "  #{f}" }
  puts "  ... and #{files.count - 10} more" if files.count > 10

  total_size = files.sum { |f| File.size(f) rescue 0 }
  puts "\nTotal size: #{total_size / 1024 / 1024}MB"

  print "\nDelete all? [y/N] "
  if gets.strip.downcase == 'y'
    files.each { |f| rm(f) }
    puts "Deleted #{files.count} files."
  end
end

Next: Next Steps

Clone this wiki locally