### Install Ruby on Ubuntu using TTY-Command Source: https://github.com/piotrmurach/tty-command/blob/master/README.md An example demonstrating how TTY-Command can be used to automate system tasks, such as installing software dependencies for a Ruby version manager on an Ubuntu machine. ```ruby cmd = TTY::Command.new # dependencies cmd.run "apt-get -y install build-essential checkinstall" ``` -------------------------------- ### Download and Install Ruby (Ruby) Source: https://github.com/piotrmurach/tty-command/blob/master/README.md This snippet checks if a specific Ruby version tarball exists, downloads it if not, extracts it, and then configures and builds Ruby. It assumes the presence of `wget` and `tar` commands and uses a `cmd.run` method for executing shell commands. ```ruby 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 ``` -------------------------------- ### Install TTY::Command Gem Source: https://context7.com/piotrmurach/tty-command/llms.txt Instructions for adding the TTY::Command gem to your project's Gemfile or installing it directly using the gem command. ```ruby # Add to Gemfile gem "tty-command" # Or install directly # $ gem install tty-command ``` -------------------------------- ### Provide Input to Command Stdin (Ruby) Source: https://context7.com/piotrmurach/tty-command/llms.txt Shows how to supply input to a command's standard input using the `:input` option with a string or the `:in` option with a `StringIO` object or file handle. Examples include multi-line input and piping data. ```ruby require "tty-command" cmd = TTY::Command.new # Simple input string out, _ = cmd.run("./cli_program", input: "Piotr\n") puts "out: #{out}" # => "Your name: Piotr" # Multi-line input with StringIO in_stream = StringIO.new in_stream.puts "username@example.com" in_stream.puts "password123" in_stream.rewind result = cmd.run("./login_cli", "login", in: in_stream) puts result.out # Input from file cmd.run(:cat, in: "input_file.txt") cmd.run(:cat, in: open("/etc/passwd")) # Piping data through command cmd.run("wc -l", input: "line1\nline2\nline3\n") ``` -------------------------------- ### Create Custom Printers for TTY::Command Output Source: https://context7.com/piotrmurach/tty-command/llms.txt Allows customization of command output formatting by extending the abstract printer class. You can define how command start, output, error, and exit events are displayed. ```ruby require "tty-command" class CustomPrinter < TTY::Command::Printers::Abstract def print_command_start(cmd, *args) output << "[START] #{cmd.to_command}\n" end def print_command_out_data(cmd, *args) output << "[OUT] #{args.join}\n" end def print_command_err_data(cmd, *args) output << "[ERR] #{args.join}\n" end def print_command_exit(cmd, status, runtime) output << "[EXIT] Status: #{status}, Runtime: #{runtime}s\n" end def write(cmd, message) output << message end end # Use custom printer cmd = TTY::Command.new(printer: CustomPrinter) cmd.run("echo 'hello'") # => [START] echo 'hello' # => [OUT] hello # => [EXIT] Status: 0, Runtime: 0.003s ``` -------------------------------- ### Basic Command Execution in Ruby with TTY::Command Source: https://github.com/piotrmurach/tty-command/blob/master/README.md Demonstrates the fundamental usage of TTY::Command for running external shell commands. It shows how to instantiate the command object and execute simple commands like 'ls -la' and 'echo'. The `run` method automatically raises an exception on command failure, providing an improvement over standard shell scripting. ```ruby require "tty-command" cmd = TTY::Command.new cmd.run("ls -la") cmd.run("echo Hello!") ``` -------------------------------- ### Run Commands in Binary Mode (Ruby) Source: https://github.com/piotrmurach/tty-command/blob/master/README.md Shows how to execute commands with standard input, output, and error streams set to binary mode. This can be specified per command or globally for all commands. ```ruby cmd.run("echo 'hello'", binmode: true) cmd = TTY::Command.new(binmode: true) ``` -------------------------------- ### Initialize TTY::Command Runner Source: https://context7.com/piotrmurach/tty-command/llms.txt Demonstrates various ways to initialize a TTY::Command runner instance with different configurations for output handling, logging, dry-run mode, and global command settings. ```ruby require "tty-command" # Basic initialization with default pretty printer cmd = TTY::Command.new # Silent execution with null printer cmd = TTY::Command.new(printer: :null) # Progress printer (dots for success, F for failure) cmd = TTY::Command.new(printer: :progress) # Quiet printer (only command output, no decorations) cmd = TTY::Command.new(printer: :quiet) # Custom output destination with Logger require "logger" logger = Logger.new("commands.log") cmd = TTY::Command.new(output: logger, color: false) # Dry-run mode (prints commands without executing) cmd = TTY::Command.new(dry_run: true) cmd.run("rm -rf /important") # => [abc123] (dry run) rm -rf /important cmd.dry_run? # => true # Disable UUID prefix in output cmd = TTY::Command.new(uuid: false) # Global timeout for all commands (5 seconds) cmd = TTY::Command.new(timeout: 5) # Global PTY mode for interactive commands cmd = TTY::Command.new(pty: true) # Binary mode for all commands cmd = TTY::Command.new(binmode: true) ``` -------------------------------- ### Redirect Command Input and Output to Files (Ruby) Source: https://github.com/piotrmurach/tty-command/blob/master/README.md Illustrates redirecting a command's input from a file and its output to a file. Supports various methods including file paths, IO objects, and explicit flags/permissions for file creation. ```ruby 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") cmd.run(:ls, :out => ["log", "w"]) cmd.run(:ls, :out => ["log", "w", 0600]) cmd.run(:ls, :out => ["log", File::WRONLY|File::EXCL|File::CREAT, 0600]) cmd.run("cat", :in => "Gemfile", :out => "gemfile.log") ``` -------------------------------- ### Configure command logging and output printers Source: https://github.com/piotrmurach/tty-command/blob/master/README.md Allows customization of how command execution and output are displayed. You can choose different printers (e.g., `:null`, `:pretty`, `:progress`, `:quiet`) and direct output to a custom logger object. Options like `:color`, `:uuid`, and `:only_output_on_error` further refine the logging behavior. ```ruby cmd = TTY::Command.new(printer: :progress) logger = Logger.new("dev.log") cmd = TTY::Command.new(output: logger) cmd = TTY::Command.new(color: true) cmd = TTY::Command.new(uuid: false) cmd.run("rm -R all_my_files") cmd.run("echo hello", uuid: false) cmd.run("non_failing_command", only_output_on_error: true) ``` -------------------------------- ### Set Environment Variables for Commands (Ruby) Source: https://github.com/piotrmurach/tty-command/blob/master/README.md Demonstrates how to set environment variables for a command execution. Variables can be passed as a hash directly or using the `:env` option. Nil values unset the variable in the child process. ```ruby cmd.run({"RAILS_ENV" => "PRODUCTION"}, :rails, "server") cmd.run(:rails, "server", env: {rails_env: :production}) cmd.run(:echo, "hello", env: {foo: "bar", baz: nil}) ``` -------------------------------- ### Test file system conditions Source: https://github.com/piotrmurach/tty-command/blob/master/README.md Provides a convenient way to perform file system tests, similar to the bash `test` command. It accepts a string representing the test expression and returns `true` if the condition is met, `false` otherwise. ```ruby if cmd.test "-e /etc/passwd" puts "Sweet..." else puts "Ohh no! Where is it?" exit 1 end ``` -------------------------------- ### Implement Custom Command Output Printer Source: https://github.com/piotrmurach/tty-command/blob/master/README.md Create and register a custom printer class to handle command execution notifications. The printer must implement at least a `write` method to process output during the command's lifecycle. ```ruby class CustomPrinter < TTY::Command::Printers::Abstract def write(cmd, message) puts cmd.to_command + message end end cmd = TTY::Command.new(printer: CustomPrinter) ``` -------------------------------- ### Execute Command with Exception on Failure (run) Source: https://context7.com/piotrmurach/tty-command/llms.txt Shows how to execute a shell command using `run` and handle potential failures by catching the `TTY::Command::ExitError` exception. It also demonstrates capturing stdout and stderr, and passing arguments safely. ```ruby require "tty-command" cmd = TTY::Command.new # Basic command execution cmd.run("ls -la") cmd.run("echo Hello!") # Capture stdout and stderr out, err = cmd.run("cat ~/.bashrc | grep alias") puts "Output: #{out}" # Command with separate arguments (auto-escaped) path = "file with spaces.txt" cmd.run("cat", path) # Arguments are automatically shell-escaped # Using symbols for commands out, _ = cmd.run(:echo, "hello world!") puts "Result: #{out}" # => "hello world!\n" # Block form for streaming output output_lines = [] error_lines = [] cmd.run("long_running_script.sh") do |out, err| output_lines << out if out error_lines << err if err end # Handle failures with exception handling begin cmd.run("exit 1") rescue TTY::Command::ExitError => e puts "Command failed: #{e.message}" # => Running `exit 1` failed with # exit status: 1 # stdout: Nothing written # stderr: Nothing written end ``` -------------------------------- ### Specify Process Termination Signal (Ruby) Source: https://github.com/piotrmurach/tty-command/blob/master/README.md Illustrates how to specify a custom termination signal for a command instead of the default SIGTERM. This allows for more control over process termination. ```ruby cmd.run("whilte test1; sleep1; done", timeout: 5, signal: :KILL) ``` -------------------------------- ### Run Command as Specific User Source: https://github.com/piotrmurach/tty-command/blob/master/README.md Execute a command as a designated user by providing the `user` option. This is useful for tasks requiring specific user permissions. ```ruby cmd.run(:echo, "hello", user: "piotr") ``` -------------------------------- ### Capturing Command Output with TTY::Command in Ruby Source: https://github.com/piotrmurach/tty-command/blob/master/README.md Illustrates how to capture the standard output (stdout) and standard error (stderr) streams from an executed command using TTY::Command. The `run` method returns an array containing stdout and stderr, which can then be used for further processing or analysis within the Ruby application. ```ruby require "tty-command" cmd = TTY::Command.new out, err = cmd.run("cat ~/.bashrc | grep alias") ``` -------------------------------- ### Execute a command using the Ruby interpreter Source: https://github.com/piotrmurach/tty-command/blob/master/README.md Runs a given string as a Ruby script using the `ruby` interpreter. This is useful for executing short Ruby snippets directly from the command line. ```ruby cmd.ruby %q{-e "puts 'Hello world'"} ``` -------------------------------- ### Set Command Execution Timeout (Ruby) Source: https://github.com/piotrmurach/tty-command/blob/master/README.md Demonstrates how to set a timeout for command execution in seconds. The timeout can be set per command or globally when creating a TTY::Command instance. ```ruby cmd.run("while test 1; sleep 1; done", timeout: 5) cmd = TTY::Command.new(timeout: 5) ``` -------------------------------- ### Run a command and raise error on failure Source: https://github.com/piotrmurach/tty-command/blob/master/README.md Similar to `run`, but `run!` will raise a `TTY::Command::ExitError` if the command exits with a non-zero status. This is useful for immediately detecting and handling command failures. ```ruby if cmd.run!("which xyzzy").failure? cmd.run("brew install xyzzy") end ``` -------------------------------- ### Wait for a pattern in command output Source: https://github.com/piotrmurach/tty-command/blob/master/README.md Pauses execution until a specified pattern is matched in the command's standard output. This is useful for monitoring long-running processes and reacting when a certain event occurs. ```ruby cmd.wait "tail -f /var/log/production.log", /something happened/ ``` -------------------------------- ### Iterate Over Command STDOUT Lines Source: https://github.com/piotrmurach/tty-command/blob/master/README.md Process the standard output of a command line by line using the `each` method. The default delimiter is a newline character, but it can be customized globally or per call. ```ruby TTY::Command.record_separator = "\n\r" cmd.run(:ls, "-1").each { |line| puts line } cmd.run(:ls, "-1").each("\t") { ... } ``` -------------------------------- ### Run Command with Specific Umask Source: https://github.com/piotrmurach/tty-command/blob/master/README.md Set the file mode creation mask for a command using the `umask` option. This controls the permissions of newly created files and directories. ```ruby cmd.run(:echo, "hello", umask: "007") ``` -------------------------------- ### Check Command Execution Status Source: https://github.com/piotrmurach/tty-command/blob/master/README.md Determine if a command executed successfully, failed, or completed its run. The `success?`, `failure?`, `failed?`, `exited?`, and `complete?` methods provide clear status indicators. ```ruby result = cmd.run(:echo, "Hello") result.success? # => true result.failure? # => false result.failed? # => false result.exited? # => true result.complete? # => true ``` -------------------------------- ### Run a command and capture output Source: https://github.com/piotrmurach/tty-command/blob/master/README.md Executes a shell command and returns its standard output and standard error. If the command fails (non-zero exit code), a TTY::Command::ExitError is raised. The `run` method can also accept a block to process output and errors as they are received. ```ruby cmd.run("cat file.txt") out, err = cmd.run("date") puts "The date is #{out}" # => "The date is Tue 10 May 2016 22:30:15 BST\n" cmd.run("long running script") do |out, err| output << out if out errors << err if err end ``` -------------------------------- ### Handle Command Timeouts (Ruby) Source: https://context7.com/piotrmurach/tty-command/llms.txt Explains how to set execution time limits for commands using the `timeout` option, which automatically terminates the process. It covers per-command timeouts, custom termination signals, and global timeouts. ```ruby require "tty-command" # Per-command timeout cmd = TTY::Command.new begin cmd.run("while true; do echo 'hello'; sleep 1; done", timeout: 5) rescue TTY::Command::TimeoutExceeded puts "Command timed out after 5 seconds" end # Custom termination signal begin cmd.run("while true; do sleep 1; done", timeout: 5, signal: :KILL) rescue TTY::Command::TimeoutExceeded puts "BOOM! Process killed" end # Global timeout for all commands cmd = TTY::Command.new(timeout: 10) cmd.run("quick_command") # inherits 10 second timeout cmd.run("slow_cmd", timeout: 60) # override with longer timeout ``` -------------------------------- ### Control Execution Context (Ruby) Source: https://context7.com/piotrmurach/tty-command/llms.txt Explains how to control the execution context of commands, including changing the working directory (`chdir`), running as a different user (`user`), belonging to a group (`group`), and setting the file creation mask (`umask`). ```ruby require "tty-command" cmd = TTY::Command.new # Change working directory cmd.run(:echo, "hello", chdir: "/var/tmp") cmd.run("ls -la", chdir: "/home/user/project") # Run as different user (requires sudo privileges) cmd.run(:echo, "hello", user: "www-data") # Run as part of group cmd.run(:echo, "hello", group: "developers") # Set umask for file creation cmd.run(:touch, "newfile.txt", umask: "007") cmd.run("./generate_files.sh", umask: "077") ``` -------------------------------- ### Redirect Command Output to Standard Error (Ruby) Source: https://github.com/piotrmurach/tty-command/blob/master/README.md Shows how to redirect a command's standard error to its standard output using shell redirection or the `:err` option. This is useful for capturing all output in one stream. ```ruby out, err = cmd.run("ls 1>&2") puts err 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) ``` -------------------------------- ### Run Commands and Check Status (Ruby) Source: https://context7.com/piotrmurach/tty-command/llms.txt Executes shell commands and provides methods to check their success, failure, and exit status. It also allows iterating over command output line by line or with custom separators. ```ruby require "tty-command" cmd = TTY::Command.new # Tuple destructuring out, err = cmd.run("date") puts "The date is #{out}" # Status checks result = cmd.run!(:ls, "/nonexistent") puts result.success? # => false puts result.failure? # => true puts result.exited? # => true # Iterate over output lines result = cmd.run(:ls, "-1") result.each { |line| puts "File: #{line}" } # => File: CHANGELOG.md # => File: Gemfile # => File: README.md # Custom line separator result = cmd.run(:echo, "a\tb\tc") result.each("\t") { |part| puts part } # Global separator change TTY::Command.record_separator = "\n\r" ``` -------------------------------- ### Change Directory for Command Execution Source: https://github.com/piotrmurach/tty-command/blob/master/README.md Execute a command within a specified directory using the `:chdir` option. This allows for localized command execution without changing the current working directory of the main Ruby process. ```ruby cmd.run(:echo, "hello", chdir: "/var/tmp") ``` -------------------------------- ### Set Environment Variables for Command Execution (Ruby) Source: https://context7.com/piotrmurach/tty-command/llms.txt Demonstrates how to set environment variables for commands executed via TTY-Command, either by passing a hash as an argument or using the `:env` option. It covers capturing output, unsetting variables, and setting multiple variables. ```ruby require "tty-command" cmd = TTY::Command.new # Environment as first argument cmd.run({"RAILS_ENV" => "production"}, :rails, "server") # Environment via :env option cmd.run(:rails, "server", env: {rails_env: :production}) # Capture environment variable output out, _ = cmd.run("env | grep FOO", env: {"FOO" => "hello"}) puts "Result: #{out}" # => "FOO=hello\n" # Unset environment variable (pass nil) cmd.run(:echo, "hello", env: {foo: "bar", baz: nil}) # Multiple environment variables cmd.run("./deploy.sh", env: { "DATABASE_URL" => "postgres://localhost/mydb", "REDIS_URL" => "redis://localhost:6379", "NODE_ENV" => "production" }) ``` -------------------------------- ### Capture Command Output (STDOUT and STDERR) Source: https://github.com/piotrmurach/tty-command/blob/master/README.md Retrieve the standard output and standard error streams from a command execution. The output can be accessed directly as a tuple or through dedicated attributes on the result object. ```ruby out, err = cmd.run(:echo, "Hello") result = cmd.run(:echo, "Hello") result.out result.err ``` -------------------------------- ### Redirect Command Output (Ruby) Source: https://context7.com/piotrmurach/tty-command/llms.txt Illustrates various methods for redirecting command output (stdout, stderr) to files, merging streams, discarding output, and setting file permissions. It covers redirecting both streams to the same file and reading from one file to another. ```ruby require "tty-command" cmd = TTY::Command.new # Redirect stdout to file out, err = cmd.run(:ls, out: "ls.log") puts "OUT>> #{out}" # => "" (written to file) # Redirect stderr to stdout (merge streams) cmd.run(:ls, err: :out) cmd.run(:ls, stderr: :stdout) cmd.run(:ls, 2 => 1) cmd.run(:ls, STDERR => STDOUT) # Separate log files for stdout and stderr cmd.run(:command, out: "stdout.log", err: "stderr.log") # Redirect both streams to same file cmd.run(:ls, [:out, :err] => "combined.log") # Discard output cmd.run(:noisy_command, out: "/dev/null") # File with specific permissions cmd.run(:ls, out: ["output.log", "w"]) # 0664 assumed cmd.run(:ls, out: ["output.log", "w", 0600]) # explicit perms cmd.run(:ls, out: ["output.log", File::WRONLY|File::EXCL|File::CREAT, 0600]) # Read from file, write to file cmd.run("cat", in: "Gemfile", out: "gemfile_copy.log") ``` -------------------------------- ### Run Command with Specific Group Source: https://github.com/piotrmurach/tty-command/blob/master/README.md Execute a command as part of a specified group using the `group` option. This helps in managing group-based access controls for command execution. ```ruby cmd.run(:echo, "hello", group: "devs") ``` -------------------------------- ### Execute Command Without Exception (run!) Source: https://context7.com/piotrmurach/tty-command/llms.txt Illustrates using the `run!` method to execute commands without raising exceptions on failure. The `TTY::Command::Result` object returned can be inspected for success or failure status. ```ruby require "tty-command" cmd = TTY::Command.new # Check if command exists before installing if cmd.run!("which xyzzy").failure? cmd.run("brew install xyzzy") end # Conditional logic based on command result result = cmd.run!("grep 'pattern' file.txt") if result.success? puts "Pattern found: #{result.out}" else puts "Pattern not found" end # Multiple condition checks result = cmd.run!("test -d /some/directory") puts result.success? # => true/false puts result.failure? # => true/false puts result.failed? # => true/false (alias) puts result.exited? # => true puts result.complete? # => true (alias) ``` -------------------------------- ### Perform a dry run of a command Source: https://github.com/piotrmurach/tty-command/blob/master/README.md Simulates command execution without actually running them. When `dry_run` is enabled, commands are printed to standard output prefixed with `(dry run)` instead of being executed. The `dry_run?` method can be used to check the current mode. ```ruby cmd = TTY::Command.new(dry_run: true) cmd.run(:rm, "all_my_files") # => [123abc] (dry run) rm all_my_files cmd.dry_run? # => true ``` -------------------------------- ### Execute Ruby Interpreter with TTY::Command Source: https://context7.com/piotrmurach/tty-command/llms.txt Runs Ruby code using the current Ruby interpreter. It can execute one-liners, scripts, or commands with arguments. ```ruby require "tty-command" cmd = TTY::Command.new # Execute Ruby one-liner cmd.ruby(%q{-e "puts 'Hello world'"}) # Run Ruby script cmd.ruby("script.rb") # Ruby with arguments cmd.ruby("-v") # => prints Ruby version # Ruby with multiple arguments cmd.ruby("-e", "puts ARGV", "--", "arg1", "arg2") ``` -------------------------------- ### Enable Pseudo Terminal (PTY) for Commands Source: https://github.com/piotrmurach/tty-command/blob/master/README.md Configure TTY::Command to run subprocesses within a pseudo-terminal. This is useful for interactive commands or those that detect terminal environments. It defaults to false and supports systems like Linux and OS X, with graceful fallback on others. Note that enabling pty can alter command behavior, such as enabling pagers for commands like 'git log'. ```ruby cmd = TTY::Command.new(pty: true) cmd.run("echo 'hello'", pty: true) ``` -------------------------------- ### Enable Pseudo-Terminal (PTY) Mode (Ruby) Source: https://context7.com/piotrmurach/tty-command/llms.txt Details how to enable pseudo-terminal mode for commands that require interactive terminal features, such as colored output. This can be set per-command or globally, and PTY mode can alter command behavior. ```ruby require "tty-command" # Per-command PTY cmd = TTY::Command.new cmd.run("./color_script.sh", pty: true) # Global PTY mode cmd = TTY::Command.new(pty: true) cmd.run("ls --color=auto") # Note: PTY changes command behavior cmd.run("git log") # => finishes, returns full output cmd.run("git log", pty: true) # => uses pager, waits for input # Suppress PTY warnings with verbose: false cmd.run("echo 'test'", pty: true, verbose: false) ``` -------------------------------- ### Wait for Pattern Match in Command Output with TTY::Command Source: https://context7.com/piotrmurach/tty-command/llms.txt Blocks execution until the output of a command matches a specified regular expression pattern. This is useful for monitoring logs or waiting for services to become ready. ```ruby require "tty-command" cmd = TTY::Command.new # Wait for specific log entry cmd.wait("tail -f /var/log/production.log", /something happened/) # Wait for service to be ready cmd.wait("docker logs -f mycontainer", /Server started/) # Wait for build completion cmd.wait("tail -f build.log", /BUILD SUCCESSFUL/) ``` -------------------------------- ### Execute Shell Test Expressions with TTY::Command Source: https://context7.com/piotrmurach/tty-command/llms.txt Executes shell test expressions and returns a boolean result. It supports various checks like file existence, readability, writability, executability, string emptiness, and value comparisons. ```ruby require "tty-command" cmd = TTY::Command.new(printer: :null) # Check if file exists if cmd.test("-e /etc/passwd") puts "Password file exists" else puts "Password file not found" exit 1 end # Check if directory exists if cmd.test("-d /var/log") puts "Log directory exists" end # Check if file is readable cmd.test("-r /etc/config") # => true/false # Check if file is writable cmd.test("-w /tmp/output") # => true/false # Check if file is executable cmd.test("-x /usr/bin/ruby") # => true/false # Check if string is empty cmd.test("-z ''") # => true # Compare values cmd.test("1 -eq 1") # => true cmd.test("'hello' = 'hello'") # => true ``` -------------------------------- ### Configure TTY::Command to Output Only on Error Source: https://context7.com/piotrmurach/tty-command/llms.txt Hides command output unless the command fails, which is useful for keeping CI/CD logs clean. Output will only be shown if the executed command returns a non-zero exit status. ```ruby require "tty-command" cmd = TTY::Command.new # Silent on success, verbose on failure cmd.run("rake test", only_output_on_error: true) # Output appears only if command fails cmd.run("bundle install", only_output_on_error: true) ``` -------------------------------- ### Automatic Argument Escaping with TTY::Command in Ruby Source: https://github.com/piotrmurach/tty-command/blob/master/README.md Shows TTY::Command's capability to automatically escape arguments passed to shell commands, preventing common issues with special characters or spaces in file paths. It contrasts manual string interpolation, which can lead to errors, with passing arguments as separate strings to the `run` method for safe execution. ```ruby require "tty-command" require "fileutils" cmd = TTY::Command.new path = "hello world" FileUtils.touch(path) # This will fail due to bad escaping # cmd.run("sum #{path}") # This gets escaped automatically cmd.run("sum", path) ``` -------------------------------- ### TTY::Command::Result Object Properties Source: https://context7.com/piotrmurach/tty-command/llms.txt Explains the properties of the `TTY::Command::Result` object, including how to access stdout, stderr, exit status, and runtime. It also mentions that the object is Enumerable. ```ruby require "tty-command" cmd = TTY::Command.new(printer: :null) # Access result properties result = cmd.run(:echo, "Hello\nWorld") puts result.out # => "Hello\nWorld\n" puts result.stdout # => alias for out puts result.err # => "" puts result.stderr # => alias for err puts result.exit_status # => 0 puts result.exitstatus # => alias puts result.status # => alias puts result.runtime # => 0.003 (seconds) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.