Skip to content
Tutorials Center
My learning

Topics

Lesson 116 of 134 ยท Web and Ecosystem

Scripting and Command-Line Tools

Write Ruby command-line tools that behave like real Unix programs. Learn ARGV, exit codes, shebangs, STDIN pipelines, stderr, colored output, and a hand-built Thor-style command dispatcher.

Ruby began as a scripting language, and it is still one of the nicest tools for gluing things together: renaming files, reshaping logs, calling APIs, running deployments. Homebrew, Chef, Vagrant and CocoaPods are all Ruby command-line programs. A good command-line tool follows the habits of Unix: it takes arguments, reads from standard input, writes results to standard output and problems to standard error, and tells the shell whether it succeeded through an exit code.

This lesson builds those habits step by step. Our runner executes one script with no command-line arguments and no terminal, so we simulate the pieces: we pass ARGV-style arrays to our own functions, preset standard input, and read the exit code the runner reports. The only things we show read-only are gems such as Thor that cannot be installed here.

A script is just a file

Save Ruby code in a file such as greet.rb and run it with ruby greet.rb. Anything on the command line after the file name becomes an element of the global array ARGV, always strings.

Terminal
# read-only example: a shell session
ruby greet.rb Ada Grace

Inside the script, ARGV is then ["Ada", "Grace"]. The runner passes no arguments, so look at what a script sees by default, and at the other constants that describe it:

Ruby What every script knows about itself

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The comparison __FILE__ == $PROGRAM_NAME is true only when the file was started directly, not when another file required it. That makes it the classic guard that lets one file be both a library and a program:

Ruby
# read-only example: a file that is both a library and a script
def main(argv)
  puts "Hello, #{argv.first || 'world'}"
end

main(ARGV) if __FILE__ == $PROGRAM_NAME

Writing a main method that takes the arguments as a parameter is more than style. It lets you test the program by calling main(["Ada"]), which is how we will exercise every example below.

Shebang lines and executable scripts

On macOS and Linux you can make a script runnable by name. Put a shebang on the first line, mark the file executable, and the shell hands it to Ruby:

Ruby
#!/usr/bin/env ruby
# read-only example: the first line of a script called "hello"
puts "Hello from an executable script"
Terminal
# read-only example: shell commands
chmod +x hello
./hello

/usr/bin/env ruby finds Ruby wherever your version manager installed it, which is more portable than a hard-coded path. Gems that ship command-line tools use the same trick: the bin/ folder holds scripts, and installing the gem puts them on your PATH.

Parsing options

Real tools accept flags (--verbose, -n 5). Ruby's standard library has OptionParser for that, covered in OptionParser and Logger. It parses a plain array, so it works on ARGV or on a test array alike. Here is a complete tool in the shape you should copy: a main method that takes argv and returns an exit code.

Ruby A tool with flags, tested by calling main

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

warn writes to standard error, so error messages never mix with the real output when someone pipes your program into another one. The runner shows both streams together. Notice how bad input becomes a friendly message and a non-zero code, and not a stack trace; that is the next topic.

Exit codes

When a program finishes it hands the shell a number between 0 and 255. 0 means success; anything else means failure. Scripts, make, CI systems and && chains all depend on it. Common conventions are 1 for a general error and 2 for a usage error. Ruby gives you three ways to set it:

  • exit or exit 0 ends with success; exit 3 ends with code 3; exit(false) is code 1.
  • abort("message") prints the message to standard error and exits with code 1.
  • An unhandled exception exits with code 1 and prints a stack trace.

Under the hood exit is just an exception, SystemExit, which is why ensure blocks still run and why you can catch it.

Ruby exit is an exception called SystemExit

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Look at the order of the last lines. exit 4 raises SystemExit; the ensure clause runs as the exception passes through; then at_exit handlers run just before the process ends. The runner reports the non-zero exit code in a note under the output. at_exit is handy for cleanup, but keep it small, and never rescue Exception in a script because that would swallow SystemExit and Interrupt too.

Let a script fail loudly. A short script that prints a stack trace and exits with code 1 is good behaviour. Only rescue errors you can actually explain to the user ("file not found: report.csv") and turn them into a clean message with a non-zero code.

Standard input and pipelines

Unix tools shine in pipelines: cat access.log | grep 404 | ruby count.rb. For that, a program reads lines from standard input (STDIN or $stdin) and writes results to standard output. gets reads one line, STDIN.each_line iterates lazily, and STDIN.read slurps everything. The special object ARGF is clever: it reads from the files named in ARGV if there are any, and from standard input otherwise, exactly like cat does. A filter written with ARGF works both ways.

The runner presets input for us.

Ruby A word-frequency filter reading STDIN

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

If you used ARGF.each_line instead of $stdin.each_line, the program would also accept ruby count.rb a.txt b.txt and read those files in order. For one-liners Ruby even has flags: ruby -ne 'puts $_ if $_ =~ /error/' log.txt is a grep; -n wraps your code in a loop over input lines and -p prints each line after your code runs. Text processing techniques are in Text Processing and Input and Output.

A few pipeline manners:

  • Print results to stdout and diagnostics to stderr.
  • Stay quiet when everything is fine; Unix tools do not chatter.
  • Handle the pipe being closed early (ruby big.rb | head): Ruby raises Errno::EPIPE, which a polite tool rescues and exits quietly.
  • Check $stdin.tty?: it is true when a person is typing and false when input is piped, so a tool can print a prompt only for humans.

Colored, formatted output by hand

Friendly tools use color and alignment. Terminals understand ANSI escape sequences: the escape character, then [, a number, m. \e[31m starts red text and \e[0m resets. Libraries such as pastel, tty-table and tty-progressbar (read-only, third-party) wrap this, but the basics fit in a few lines. A polite tool turns color off when output is not a terminal, or when the NO_COLOR environment variable is set.

Ruby Color, table and progress output without gems

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Because there is no terminal here, $stdout.tty? is false and Paint returns plain text, which is the right behaviour for pipes, log files and CI. On your machine you would see colors. The \r (carriage return) character moves the cursor back to the start of the line, so a real progress bar redraws itself with print "\r#{progress(i, n)}" and $stdout.flush.

Subcommands in the style of Thor

Many tools have subcommands: git commit, bundle install, rails new. The popular Thor gem builds them from a class where each public method is a command. This is a read-only example, because Thor is not installed on this runner:

Ruby
# read-only example: needs the thor gem
require "thor"

class Tasks < Thor
  desc "add TEXT", "Add a task"
  option :priority, type: :numeric, default: 1
  def add(text)
    puts "Added #{text} (priority #{options[:priority]})"
  end

  desc "list", "List all tasks"
  def list
    puts "..."
  end

  def self.exit_on_failure? = true
end

Tasks.start(ARGV)

Thor reads the class to generate help, parse flags and report wrong usage. We can build a small version of the same idea with reflection (Reflection and Introspection) and a command macro: each registered command is a method, and a dispatcher looks the word up.

Ruby A Thor-style command dispatcher

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Each call creates a fresh Tasks object, so list sees no tasks: a real tool keeps its data in a file (see Files and IO). Two Ruby features carry the design. The desc call remembers a description, and the method_added hook (Hooks and Callbacks) fires when the next method is defined, pairing them up. And Method#arity tells the dispatcher how many arguments a command wants, which is how it produces the "called with 0 arguments" error.

Habits of a polished tool

  • Put logic in methods that return values; keep the thin shell around them. The main(argv) function, tested by calling it, is the single most useful pattern.
  • Respect the streams. Results to stdout, messages to stderr, so tool > out.txt still shows the errors.
  • Use Pathname, FileUtils and Tempfile for files (Tempfile, Pathname and FileUtils), and never build shell commands with string interpolation.
  • Give --help and a useful usage line, even for scripts only you use. Future you counts.
  • Handle Ctrl-C. Interrupt is raised on SIGINT; catch it at the top level, clean up, and exit with code 130, the shell convention.
  • Make it idempotent when you can: running a deployment script twice should not break anything.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does ARGV contain for the command ruby tool.rb --fast data.csv?

    ARGV holds only the arguments after the script name, as plain strings. Turning them into options is the job of OptionParser or similar.
  2. 2. What exit code means success?

    By Unix convention, 0 is success and any other value signals an error. Shells and CI systems rely on this.
  3. 3. Why does an ensure block still run after exit 4?

    exit raises SystemExit, so ordinary exception unwinding runs ensure clauses, and at_exit handlers run just before the process ends.
  4. 4. Where should error messages go in a well-behaved command-line tool?

    Sending diagnostics to stderr keeps stdout clean for pipes and redirects, so the next program in the pipeline sees only real data.
  5. 5. What is ARGF useful for?

    ARGF behaves like cat: it concatenates the files given as arguments and falls back to STDIN, so one filter handles both usages.

Summary

  • ARGV holds the command-line arguments as strings; __FILE__ == $PROGRAM_NAME tells you the file was run directly.
  • Write a main(argv) method that returns an exit code, so you can test the tool without a terminal.
  • Exit code 0 means success; exit, abort and unhandled exceptions set the others, and exit is the exception SystemExit.
  • Send results to stdout and diagnostics to stderr (warn); read pipelines from $stdin or ARGF.
  • ANSI codes make color and progress bars; check $stdout.tty? and NO_COLOR before using them.
  • Gems like Thor and OptionParser structure subcommands and flags; a few lines of reflection reproduce the core idea.

Next: The Ruby Ecosystem