Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Ruby > Shell Scripts

Tristan Hume
February 06, 2013

Ruby > Shell Scripts

Presentation I gave at the Ottawa Ruby Group on replacing shell scripts with Ruby.

Tristan Hume

February 06, 2013
Tweet

More Decks by Tristan Hume

Other Decks in Programming

Transcript

  1. A Smooth Transition • Backticks: `ps -ax`.lines.map(&:split) • Handy Methods:

    ◦ File.foreach("words.txt") {|line| puts line.capitalize} • Dir[]: ◦ Dir['**/*.rb'].each {|file| code_files << file }
  2. Have No Fear: FileUtils is here! require "fileutils" FileUtils.cp some_file,

    some_file + ".bak" FileUtils.rm_rf "trash" FileUtils.ln_s 'verylongsourcefilename.c', 'c', :force => true FileUtils.chown nil, 'bin', Dir['/usr/bin/*'], :verbose => true
  3. Awesomeness Comes In Many Forms data.with_progress do |item| data.with_progress.map do

    |item| # Any enumerable and any enumerable method (1..100000).with_progress.each_cons do |item| 10.times_with_progress('Counting to 10') do |i| (1..10).with_progress('Outer').map do |a| (1..10).with_progress('Middle').map do |b| # Nesting! end end
  4. An exhilarating wrapper for all things shell. (you can use

    IRB as your login shell if you really want to...) gem install rush
  5. require 'rush' file = Rush['/tmp/myfile'] file.write "hello" puts file.contents file.destroy

    puts Rush.my_process.pid puts Rush.processes.size puts Rush.bash("echo SHELL COMMAND | tr A-Z a-z") puts Rush.launch_dir['*.rb'].search(/Rush/).entries.inspect # Remote Execution local = Rush::Box.new('localhost') remote = Rush::Box.new('my.remote.server.com') local_dir = local['/Users/adam/myproj/'] remote_dir = remote['/home/myproj/app/']
  6. $ chitin ~/src/chitin % ls ~/src/chitin % ll = ls

    -:al ~/src/chitin % hg.stat ~/src/chitin % hg.stat | wc | L {|i| i.size } ~/src/chitin % git.status > '/tmp/test.out' ~/src/chitin % 44 - 2 ~/src/chitin % _ + 5 ~/src/chitin % wget "http://thume.ca/" ~/src/chitin % _ # run the same command again # You can also use Chitin as a library Shell Commands in Valid Ruby
  7. "This is all crappy Unix stuff, what's in it for

    me?" - Possibly some audience member Using Windows?
  8. WIN32OLE FTW! require 'win32ole' excel = WIN32OLE.new('Excel.Application') excel.visible = true

    workbook = excel.Workbooks.Add(); worksheet = workbook.Worksheets(1); worksheet.Range("A1:D1").value = ["North"," South","East","West"]; worksheet.Range("A2:B2").value = [5.2, 10]; worksheet.Range("C2").value = 8; worksheet.Range("D2").value = 20;
  9. TL;DR • Ruby has awesome utilities for scripting • There

    are some great gems like "progress" to help. • Never touch Visual Basic or Bash Scripting again, you won't regret it.