Skip to content

Command Chaining

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

Command Chaining

RubyShell supports shell operators for building pipelines and command chains.

Pipe Operator (|)

Chain commands using the pipe operator:

sh do
  chain { cat("file.txt") | grep("error") | wc("-l") }
end

Bang Pattern

Commands ending with ! return a Command object without executing. This allows building chains:

sh do
  # Build a pipeline
  result = (cat!("data.csv") | sort! | uniq!).exec

  # Or step by step
  cmd = cat!("file.txt")
  cmd = cmd | grep!("pattern")
  cmd.exec
end

File Redirection

Write to file (>)

sh do
  chain { echo("hello") > "output.txt" }
end

Append to file (>>)

sh do
  chain { echo("another line") >> "output.txt" }
end

Stdin Piping with _stdin

Pass input to a command:

# From a string
sh.wc("-l", _stdin: "line1\nline2\nline3")

# From another command's output
output = sh.cat("source.txt")
sh.grep("pattern", _stdin: output)

Background Execution (&)

Run commands in the background:

sh do
  chain { sleep("10") & }
end

Logical Operators

AND (&&)

Execute second command only if first succeeds:

sh do
  chain { mkdir("test") && cd("test") }
end

Chain Block

The chain block provides a context for building command chains:

sh do
  result = chain do
    cat("access.log") | grep("404") | sort | uniq("-c") | sort("-rn") | head("-10")
  end
  puts result
end

Next: Error Handling

Clone this wiki locally