Skip to content

Instantly share code, notes, and snippets.

@roryokane
Last active September 30, 2020 12:53
Show Gist options
  • Save roryokane/47c403972735bf92c8a87510fad762dc to your computer and use it in GitHub Desktop.
Save roryokane/47c403972735bf92c8a87510fad762dc to your computer and use it in GitHub Desktop.
Ruby cheat sheet – how to run a system command (shell command) and know whether it failed

The below file is a Markdown conversion of a section of an OmniOutliner document I once wrote. The nested lists below were meant to be collapsed by default, so you could expand only the branches you care about. Sadly, that’s not easy to represent in Markdown, so below you see every detail about every option.

Ruby

Run a system command (shell command) and know whether it failed

  • if you don’t need to pass STDIN to the command
    • if you don’t care about output: system
      • if you are passing arguments to the command
        • system('rm', '-r', directory) or raise "Failed to remove #{directory}"
        • if you have more complicated error handling
          • command_successful = system('rm', '-r', directory)
            unless command_successful
              # complicated error handling
            end
      • if you aren’t passing any arguments to the command
        • system(["ls", "ls"])
        • This is better than system("ls"), which tells the shell to run ls instead of running ls directly.
      • The return value of system is true if the command ran successfully and falsey if it ran unsuccessfully or failed to run.
    • if you want to capture STDOUT: Open3.capture2
      • require 'open3'
        
        stdout, status = Open3.capture2('diskutil', 'info', 'disk0')
        unless status.success?
          raise "the command failed"
        end
        
        puts stdout
    • if you want to capture STDOUT and STDERR: Open3.capture3
      • require 'open3'
        
        stdout, stderr, status = Open3.capture3('example', '--arg')
        unless status.success?
          raise "the command failed"
        end
        
        puts stdout
        $stderr.puts stderr
  • if you do need to pass STDIN to the command
    • I didn’t research this in detail yet, but I bet the solution is the Open3 standard library again, and its methods like popen2.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment