Processes, Shell Scripting and System Interaction
Ruby is excellent for automation scripts: file processing, deployment tasks, report generation, system administration. Use #!/usr/bin/env ruby shebangs and chmod +x.
output = `ls -la` # backticks: capture stdout
system("git", "status") # run; returns true/false/nil (arguments as an array avoid the shell)
exit_status = $?.exitstatus
pid = spawn("sleep 2"); Process.wait(pid)
exec("vim", "file.txt") # replace the current process
require "open3"
stdout, stderr, status = Open3.capture3("git", "log", "-1", "--oneline")
Open3.popen3("grep error") { |stdin, stdout, stderr, wait_thr| stdin.puts "error 1"; stdin.close; puts stdout.read }
ENV["HOME"]; ENV.fetch("API_KEY", "dev-key")
ARGV # command-line arguments
Process.pid; Process.ppid
trap("INT") { puts "Interrupted"; exit }
at_exit { puts "Cleaning up" }
require "shellwords"
Shellwords.escape("file with spaces.txt"); "a 'b c'".shellsplit
require "etc"
Etc.nprocessors; Etc.getlogin
RbConfig::CONFIG["host_os"]
Gem.win_platform?