Monday, January 23, 2012 at 1:48PM Bash vs Ruby
I was recently asked by a colleague if I could help out with a bash script that would scp a file to a remote server and then move the local file if the scp was successful. I have dabbled with bash for many years now, but I never went deep enough to do the more advanced stuff, so I said I couldn’t help him.
However, I did manage to learn Ruby (with a lot less effort than that of learning bash) and it has excellent support for running bash commands. So, I hacked together a script that would do the same thing in Ruby. Here’s what it looks like:
files = ['file1.txt', 'file2.txt'];
destinations = ['', '/will/fail.txt'];
files.each_with_index do |file, index|
destination = destinations[index];
puts "Moving #{file} to somehost:#{destination}";
`scp #{file} somehost:#{destination}`;
if ($?.success?)
puts "Success, moving file.";
`mv #{file} 'success'`;
else
puts "Failed, file remains.";
end
end
If you don’t know any Ruby, I’ll just walk you through it. First I define two lists, a list of files and a list of destinations. I then iterate over the list of files with the .each_with_index method. Inside the pipes, I define the item that I will get on each iteration as “file” and the index as “index”. I then fetch the destination from the list of destinations, print the file name and destination and then I run scp. Note that you have to put #{} around the variable names in the command. The back tick means “run this on the command line”.
After the scp has finished, I check the result with $?.success?. This seems a bit arcane and there might be a better way to do it (suggestions are welcome in the comments), but it works. If successful, I then move the file locally, else I print a message and let the file remain.
When you present this to a bash guy, there’s going to be resistance. Things like “I have to learn a new language” and “bash is readily available, Ruby is not” will probably be mentioned. However, given that the syntax of Ruby is so straightforward, I think there are huge benefits in terms of readability and maintenance. Regarding the “availability” argument, it’s very fast and easy to install Ruby, if it’s not already there. If you have a Mac, try starting the terminal and typing “irb”, you might be surprised. Final argument, learning a new language (especially Ruby) is fun!
What do you think, should we stick with bash for command line “apps”, or is the investment in something like Ruby worth it? Your comments are much appreciated!
Posted by Viktor Nordling
Agile Digital Editor | |
Post a Comment 
Reader Comments