• Stars
    star
    400
  • Rank 107,843 (Top 3 %)
  • Language
    Ruby
  • License
    MIT License
  • Created over 8 years ago
  • Updated 11 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Execute shell commands with pretty output logging and capture stdout, stderr and exit status.
TTY Toolkit logo

TTY::Command

Gem Version Actions CI Build status Code Climate Coverage Status

Run external commands with pretty output logging and capture stdout, stderr and exit status. Redirect stdin, stdout and stderr of each command to a file or a string.

TTY::Command provides independent command execution component for TTY toolkit.

Motivation

Complex software projects aren't just a single app. These projects usually spawn dozens or hundreds of supplementary standalone scripts which are just as important as the app itself. Examples include - data validation, deployment, monitoring, database maintenance, backup & restore, configuration management, crawling, ETL, analytics, log file processing, custom reports, etc. One of the contributors to TTY::Command counted 222 scripts in the bin directory for his startup.

Why should we be handcuffed to sh or bash for these scripts when we could be using Ruby? Ruby is easier to write and more fun, and we gain a lot by using a better language. It's nice for everyone to just use Ruby everywhere.

TTY::Command tries to add value in other ways. It'll halt automatically if a command fails. It's easy to get verbose or quiet output as appropriate, or even capture output and parse it with Ruby. Escaping arguments is a breeze. These are all areas where traditional shell scripts tend to fall flat.

Installation

Add this line to your application's Gemfile:

gem "tty-command"

And then execute:

$ bundle

Or install it yourself as:

$ gem install tty-command

Contents

1. Usage

Create a command instance and then run some commands:

require "tty-command"

cmd = TTY::Command.new
cmd.run("ls -la")
cmd.run("echo Hello!")

Note that run will throw an exception if the command fails. This is already an improvement over ordinary shell scripts, which just keep on going when things go bad. That usually makes things worse.

You can use the return value to capture stdout and stderr:

out, err = cmd.run("cat ~/.bashrc | grep alias")

Instead of using a plain old string, you can break up the arguments and they'll get escaped if necessary:

path = "hello world"
FileUtils.touch(path)
cmd.run("sum #{path}")  # this will fail due to bad escaping
cmd.run("sum", path)    # this gets escaped automatically

2. Interface

2.1 Run

Run starts the specified command and waits for it to complete.

The argument signature of run is as follows:

run([env], command, [argv1, ...], [options])

The env, command and options arguments are described in the following sections.

For example, to display file contents:

cmd.run("cat file.txt")

If the command succeeds, a TTY::Command::Result is returned that records stdout and stderr:

out, err = cmd.run("date")
puts "The date is #{out}"
# => "The date is Tue 10 May 2016 22:30:15 BST\n"

You can also pass a block that gets invoked anytime stdout and/or stderr receive output:

cmd.run("long running script") do |out, err|
  output << out if out
  errors << err if err
end

If the command fails (with a non-zero exit code), a TTY::Command::ExitError is raised. The ExitError message will include:

  • the name of command executed
  • the exit status
  • stdout bytes
  • stderr bytes

If the error output is very long, the stderr may contain only a prefix, number of omitted bytes and suffix.

2.2 Run!

If you expect a command to fail occasionally, use run! instead. Then you can detect failures and respond appropriately. For example:

if cmd.run!("which xyzzy").failure?
  cmd.run("brew install xyzzy")
end

2.3 Logging

By default, when a command is run, the command and the output are printed to stdout using the :pretty printer. If you wish to change printer you can do so by passing a :printer option:

  • :null - no output
  • :pretty - colorful output
  • :progress - minimal output with green dot for success and F for failure
  • :quiet - only output actual command stdout and stderr

like so:

cmd = TTY::Command.new(printer: :progress)

By default the printers log to stdout but this can be changed by passing an object that responds to << message:

logger = Logger.new("dev.log")
cmd = TTY::Command.new(output: logger)

You can force the printer to always in print in color by passing the :color option:

cmd = TTY::Command.new(color: true)

If the default printers don't meet your needs you can always create a custom printer

2.3.1 Color

When using printers you can switch off coloring by using :color option set to false.

2.3.2 UUID

By default, when logging is enabled and pretty printer is used, each log entry is prefixed by specific command run uuid number. This number can be switched off using the :uuid option at initialization:

cmd = TTY::Command.new(uuid: false)
cmd.run("rm -R all_my_files")
# =>
#  Running rm -r all_my_files
#  ...
#  Finished in 6 seconds with exit status 0 (successful)

or individually per command run:

cmd = TTY::Command.new
cmd.run("echo hello", uuid: false)
# =>
#  Running echo hello
#      hello
#  Finished in 0.003 seconds with exit status 0 (successful)

2.3.3 Only output on error

When using a command that can fail, setting :only_output_on_error option to true hides the output if the command succeeds:

cmd = TTY::Command.new
cmd.run("non_failing_command", only_output_on_error: true)

This will only print the Running and Finished lines, while:

cmd.run("non_failing_command")

will also print any output that the non_failing_command might generate.

Running either:

cmd.run("failing_command", only_output_on_error: true)

either:

cmd.run("failing_command")

will also print the output.

Setting this option will cause the output to show at once, at the end of the command.

2.3.4 Verbose

By default commands will produce warnings when, for example pty option is not supported on a given platform. You can switch off such warnings with :verbose option set to false.

cmd.run("echo '\e[32mColors!\e[0m'", pty: true, verbose: false)

2.4 Dry run

Sometimes it can be useful to put your script into a "dry run" mode that prints commands without actually running them. To simulate execution of the command use the :dry_run option:

cmd = TTY::Command.new(dry_run: true)
cmd.run(:rm, "all_my_files")
# => [123abc] (dry run) rm all_my_files

To check what mode the command is in use the dry_run? query helper:

cmd.dry_run? # => true

2.5 Wait

If you need to wait for a long running script and stop it when a given pattern has been matched use wait like so:

cmd.wait "tail -f /var/log/production.log", /something happened/

2.6 Test

To simulate classic bash test command you case use test method with expression to check as a first argument:

if cmd.test "-e /etc/passwd"
  puts "Sweet..."
else
  puts "Ohh no! Where is it?"
  exit 1
end

2.7 Ruby interpreter

In order to run a command with Ruby interpreter do:

cmd.ruby %q{-e "puts 'Hello world'"}

3. Advanced Interface

3.1 Environment variables

The environment variables need to be provided as hash entries, that can be set directly as a first argument:

cmd.run({"RAILS_ENV" => "PRODUCTION"}, :rails, "server")

or as an option with :env key:

cmd.run(:rails, "server", env: {rails_env: :production})

When a value in env is nil, the variable is unset in the child process:

cmd.run(:echo, "hello", env: {foo: "bar", baz: nil})

3.2 Options

When a hash is given in the last argument (options), it allows to specify a current directory, umask, user, group and zero or more fd redirects for the child process.

3.2.1 Redirection

There are few ways you can redirect commands output.

You can directly use shell redirection like so:

out, err = cmd.run("ls 1&>2")
puts err
# =>
# CHANGELOG.md
# CODE_OF_CONDUCT.md
# Gemfile
# ...

You can provide redirection as additional hash options where the key is one of :in, :out, :err, an integer (a file descriptor for the child process), an IO or array. For example, stderr can be merged into stdout as follows:

cmd.run(:ls, :err => :out)
cmd.run(:ls, :stderr => :stdout)
cmd.run(:ls, 2 => 1)
cmd.run(:ls, STDERR => :out)
cmd.run(:ls, STDERR => STDOUT)

The hash key and value specify a file descriptor in the child process (stderr & stdout in the examples).

You can also redirect to a file:

cmd.run(:cat, :in => "file")
cmd.run(:cat, :in => open("/etc/passwd"))
cmd.run(:ls, :out => "log")
cmd.run(:ls, :out => "/dev/null")
cmd.run(:ls, :out => "out.log", :err => "err.log")
cmd.run(:ls, [:out, :err] => "log")
cmd.run("ls 1>&2", :err => "log")

It is possible to specify flags and permissions of file creation explicitly by passing an array value:

cmd.run(:ls, :out => ["log", "w"]) # 0664 assumed
cmd.run(:ls, :out => ["log", "w", 0600])
cmd.run(:ls, :out => ["log", File::WRONLY|File::EXCL|File::CREAT, 0600])

You can, for example, read data from one source and output to another:

cmd.run("cat", :in => "Gemfile", :out => "gemfile.log")

3.2.2 Handling Input

You can provide input to stdin stream using the :input key. For instance, given the following executable called cli that expects name from stdin:

name = $stdin.gets
puts "Your name: #{name}"

In order to execute cli with name input do:

cmd.run("cli", input: "Piotr\n")
# => Your name: Piotr

Alternatively, you can pass input via the :in option, by passing a StringIO Object. This object might have more than one line, if the executed command reads more than once from STDIN.

Assume you have run a program, that first asks for your email address and then for a password:

in_stream = StringIO.new
in_stream.puts "[email protected]"
in_stream.puts "password"
in_stream.rewind

cmd.run("my_cli_program", "login", in: in_stream).out

3.2.3 Timeout

You can timeout command execution by providing the :timeout option in seconds:

cmd.run("while test 1; sleep 1; done", timeout: 5)

And to set it for all commands do:

cmd = TTY::Command.new(timeout: 5)

Please run examples/timeout.rb to see timeout in action.

3.2.4 Binary mode

By default the standard input, output and error are non-binary. However, you can change to read and write in binary mode by using the :binmode option like so:

cmd.run("echo 'hello'", binmode: true)

To set all commands to be run in binary mode do:

cmd = TTY::Command.new(binmode: true)

3.2.5 Signal

You can specify process termination signal other than the default SIGTERM:

cmd.run("whilte test1; sleep1; done", timeout: 5, signal: :KILL)

3.2.6 PTY(pseudo terminal)

The :pty configuration option causes the command to be executed in subprocess where each stream is a pseudo terminal. By default this options is set to false.

If you require to interface with interactive subprocess then setting this option to true will enable a pty terminal device. For example, a command may emit colored output only if it is running via terminal device. You may also wish to run a program that waits for user input, and simulates typing in commands and reading responses.

This option will only work on systems that support BSD pty devices such as Linux or OS X, and it will gracefully fallback to non-pty device on all the other.

In order to run command in pseudo terminal, either set the flag globally for all commands:

cmd = TTY::Command.new(pty: true)

or individually for each executed command:

cmd.run("echo 'hello'", pty: true)

Please note that setting :pty to true may change how the command behaves. It's important to understand the difference between interactive and non-interactive modes. For example, executing git log to view the commit history in default non-interactive mode:

cmd.run("git log") # => finishes and produces full output

However, in interactive mode with pty flag on:

cmd.run("git log", pty: true) # => uses pager and waits for user input (never returns)

In addition, when pty device is used, any input to command may be echoed to the standard output, as well as some redirects may not work.

3.2.7 Current directory

To change directory in which the command is run pass the :chdir option:

cmd.run(:echo, "hello", chdir: "/var/tmp")

3.2.8 User

To run command as a given user do:

cmd.run(:echo, "hello", user: "piotr")

3.2.9 Group

To run command as part of group do:

cmd.run(:echo, "hello", group: "devs")

3.2.10 Umask

To run command with umask do:

cmd.run(:echo, "hello", umask: "007")

3.3 Result

Each time you run command the stdout and stderr are captured and return as result. The result can be examined directly by casting it to tuple:

out, err = cmd.run(:echo, "Hello")

However, if you want to you can defer reading:

result = cmd.run(:echo, "Hello")
result.out
result.err

3.3.1 success?

To check if command exited successfully use success?:

result = cmd.run(:echo, "Hello")
result.success? # => true

3.3.2 failure?

To check if command exited unsuccessfully use failure? or failed?:

result = cmd.run(:echo, "Hello")
result.failure?  # => false
result.failed?   # => false

3.3.3 exited?

To check if command ran to completion use exited? or complete?:

result = cmd.run(:echo, "Hello")
result.exited?    # => true
result.complete?  # => true

3.3.4 each

The result itself is an enumerable and allows you to iterate over the stdout output:

result = cmd.run(:ls, "-1")
result.each { |line| puts line }
# =>
#  CHANGELOG.md
#  CODE_OF_CONDUCT.md
#  Gemfile
#  Gemfile.lock
#  ...
#  lib
#  pkg
#  spec
#  tasks

By default the linefeed character \n is used as a delimiter but this can be changed either globally by calling record_separator:

TTY::Command.record_separator = "\n\r"

or configured per each call by passing delimiter as an argument:

cmd.run(:ls, "-1").each("\t") { ... }

3.4 Custom printer

If the built-in printers do not meet your requirements you can create your own. A printer is a regular Ruby class that can be registered through :printer option to receive notifications about received command data.

As the command runs the custom printer will be notified when the command starts, when data is printed to stdout, when data is printed to stderr and when the command exits.

Please see lib/tty/command/printers/abstract.rb for a full set of methods that you can override.

At the very minimum you need to specify the write method that will be called during the lifecycle of command execution. The write accepts two arguments, first the currently run command instance and second the message to be printed:

CustomPrinter < TTY::Command::Printers::Abstract
  def write(cmd, message)
    puts cmd.to_command + message
  end
end

cmd = TTY::Command.new(printer: CustomPrinter)

4. Example

Here's a slightly more elaborate example to illustrate how tty-command can improve on plain old shell scripts. This example installs a new version of Ruby on an Ubuntu machine.

cmd = TTY::Command.new

# dependencies
cmd.run "apt-get -y install build-essential checkinstall"

# fetch ruby if necessary
if !File.exists?("ruby-2.3.0.tar.gz")
  puts "Downloading..."
  cmd.run "wget http://ftp.ruby-lang.org/pub/ruby/2.3/ruby-2.3.0.tar.gz"
  cmd.run "tar xvzf ruby-2.3.0.tar.gz"
end

# now install
Dir.chdir("ruby-2.3.0") do
  puts "Building..."
  cmd.run "./configure --prefix=/usr/local"
  cmd.run "make"
end

Development

After checking out the repo, run bin/setup to install dependencies. Then, run rake spec to run the tests. You can also run bin/console for an interactive prompt that will allow you to experiment.

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/piotrmurach/tty-command. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the Contributor Covenant code of conduct.

License

The gem is available as open source under the terms of the MIT License.

Copyright

Copyright (c) 2016 Piotr Murach. See LICENSE for further details.

More Repositories

1

tty

Toolkit for developing sleek command line apps.
Ruby
2,505
star
2

tty-prompt

A beautiful and powerful interactive command line prompt
Ruby
1,467
star
3

github

Ruby interface to GitHub API
Ruby
1,151
star
4

finite_machine

A minimal finite state machine with a straightforward syntax.
Ruby
807
star
5

pastel

Terminal output styling with intuitive and clean API.
Ruby
638
star
6

rspec-benchmark

Performance testing matchers for RSpec
Ruby
602
star
7

tty-spinner

A terminal spinner for tasks that have non-deterministic time frame.
Ruby
428
star
8

tty-progressbar

Display a single or multiple progress bars in the terminal.
Ruby
422
star
9

loaf

Manages and displays breadcrumb trails in Rails app - lean & mean.
Ruby
407
star
10

tty-markdown

Convert a markdown document or text into a terminal friendly output.
Ruby
307
star
11

tty-logger

A readable, structured and beautiful logging for the terminal
Ruby
294
star
12

github_cli

GitHub on your command line. Use your terminal, not the browser.
Ruby
266
star
13

tty-table

A flexible and intuitive table generator
Ruby
190
star
14

tty-box

Draw various frames and boxes in your terminal window
Ruby
183
star
15

awesome-ruby-cli-apps

A curated list of awesome command-line applications in Ruby.
Ruby
169
star
16

rack-policy

Rack middleware for the EU ePrivacy Directive compliance in Ruby Web Apps
Ruby
147
star
17

tty-pie

Draw pie charts in your terminal window
Ruby
140
star
18

necromancer

Conversion from one object type to another with a bit of black magic.
Ruby
135
star
19

strings

A set of useful functions for transforming strings.
Ruby
129
star
20

coinpare

Compare cryptocurrency trading data across multiple exchanges and blockchains in the comfort of your terminal
Ruby
113
star
21

tty-exit

Terminal exit codes.
Ruby
99
star
22

strings-case

Convert strings between different cases.
Ruby
97
star
23

tty-reader

A set of methods for processing keyboard input in character, line and multiline modes.
Ruby
89
star
24

tty-screen

Terminal screen detection - cross platform, major ruby interpreters
Ruby
86
star
25

tty-option

A declarative command-line parser
Ruby
85
star
26

merkle_tree

A merkle tree is a data structure used for efficiently summarizing sets of data, often one-time signatures.
Ruby
82
star
27

verse

[DEPRECATED] Text transformations
Ruby
71
star
28

tty-cursor

Terminal cursor movement and manipulation of cursor properties such as visibility
Ruby
70
star
29

tty-file

File manipulation utility methods
Ruby
67
star
30

supervision

Write distributed systems that are resilient and self-heal.
Ruby
65
star
31

tty-config

A highly customisable application configuration interface for building terminal tools.
Ruby
63
star
32

tty-font

Terminal fonts
Ruby
60
star
33

benchmark-trend

Measure performance trends of Ruby code
Ruby
60
star
34

lex

Lex is an implementation of lex tool in Ruby.
Ruby
56
star
35

tty-tree

Print directory or structured data in a tree like format
Ruby
56
star
36

strings-truncation

Truncate strings with fullwidth characters and ANSI codes.
Ruby
50
star
37

slideck

Present Markdown-powered slide decks in the terminal.
Ruby
44
star
38

tty-pager

Terminal output paging - cross-platform, major ruby interpreters
Ruby
40
star
39

tty-color

Terminal color capabilities detection
Ruby
35
star
40

tty-link

Hyperlinks in your terminal
Ruby
32
star
41

strings-inflection

Convert between singular and plural forms of English nouns
Ruby
31
star
42

tty-platform

Operating system detection
Ruby
29
star
43

tty-sparkline

Sparkline charts for terminal applications.
Ruby
29
star
44

tty-editor

Opens a file or text in the user's preferred editor
Ruby
28
star
45

communist

Library for mocking CLI calls to external APIs
Ruby
25
star
46

splay_tree

A self-balancing binary tree optimised for fast access to frequently used nodes.
Ruby
24
star
47

equatable

Allows ruby objects to implement equality comparison and inspection methods.
Ruby
24
star
48

minehunter

Terminal mine hunting game.
Ruby
23
star
49

rotation.js

Responsive and mobile enabled jQuery plugin to help create rotating content.
JavaScript
22
star
50

strings-ansi

Handle ANSI escape codes in strings
Ruby
20
star
51

benchmark-malloc

Trace memory allocations and collect stats
Ruby
20
star
52

strings-numeral

Express numbers as string numerals
Ruby
20
star
53

tty-which

Cross-platform implementation of Unix `which` command
Ruby
19
star
54

benchmark-perf

Benchmark execution time and iterations per second
Ruby
13
star
55

tty-runner

A command routing tree for terminal applications
Ruby
12
star
56

queen

English language linter to hold your files in high esteem.
Ruby
8
star
57

impact

Ruby backend for Impact.js framework
Ruby
8
star
58

pastel-cli

CLI tool for intuitive terminal output styling
Ruby
7
star
59

dotfiles

Configuration files for Unix tools
Vim Script
7
star
60

tty-markdown-cli

CLI tool for displaying nicely formatted Markdown documents in the terminal
Ruby
6
star
61

static_deploy

Automate deployment of static websites
Ruby
6
star
62

tenpin

Terminal tenpin bowling game
Ruby
4
star
63

tty.github.io

TTY toolkit website.
SCSS
3
star
64

tytus

Helps you manage page titles in your Rails app.
Ruby
3
star
65

peter-murach.github.com

Personal webpage
JavaScript
2
star
66

wc.rb

A Ruby clone of Unix wc utility.
Ruby
2
star
67

exportable

Rails plugin to ease exporting tasks.
Ruby
1
star
68

capistrano-git-stages

Multistage capistrano git tags
Ruby
1
star
69

leek

Cucumber steps and RSpec expectations for command line apps
Ruby
1
star
70

tabster

Ruby
1
star
71

unicorn.github.io

Website for the github_api and github_cli ruby gems.
CSS
1
star
72

tty-color-cli

CLI tool for terminal color capabilities detection
Ruby
1
star
73

finite_machine.github.io

Website for finite_machine Ruby gem
SCSS
1
star
74

strings-wrapping

Wrap strings with fullwidth characters and ANSI codes
Ruby
1
star