Why and when to use shell instead of Ruby

Since I am conversant in Ruby, I am about to script a few things on OSX using it. But then I thought, perhaps I am missing the boat. I know a lot of reasons to prefer Ruby over Bash (or whatever sh-compatible command language interpreter), but I don't know any reasons not to. What is the upside of programming the shell directly?

I intend to take advantage of system commands using system whenever necessary.

Note: I already know that Ruby won't always be there, but I'm interested in mostly technical, semantic and syntactic criteria.

Edit: By Ruby not always being there, I mean that it is not a standard part of all *nix distributions, unlike vi .


The shell's programming language is awful for all but one thing.

Pipelines.

The shell's programming language for pipelines totally rocks.

The | , & and ; operators, plus () and ``` form a tidy little language for describing pipelines.

a & b is concurrent

a ; b a ; b is sequential

a | b a | b is a pipeline where a feeds b

That part of shell programming rocks.

Think of ( a & b & c ) | tee capture | analysis ( a & b & c ) | tee capture | analysis ( a & b & c ) | tee capture | analysis as the kind of thing that's hard to express in Python (or Ruby). You can do much of this with iterpipes, but not quite all of it.

Much of the rest you can live without, and use Python (or Ruby) and you'll be happier and more productive.

The biggest thing to watch out for is anything involving expr at the shell level. As soon as you start trying to do "calculations", you've crossed out of the shell's sweet spot and you should stop programming in the shell and rethink what you're doing.


Ruby has a massive advantage: you know Ruby and (I assume) you don't know Bash that well!

Personally I use Ruby for complex scripts and Bash for simple ones -- the breakpoint for me is usually anything that actually has a proper set of command line parameters -- but then, I know both Bash and Ruby.

I would advise you to use Bash for anything that is simple enough that you can work it out on the commandline beforehand, for example:

who |grep -i admin |cut -c10-20 

-- and use Ruby for anything else


The core functionality in bash is to run other command line applications. Making those programs interact with each other etc. This is not what ruby is designed for (right?).

链接地址: http://www.djcxy.com/p/72.html

上一篇: 如何克隆Git中的所有远程分支?

下一篇: 为什么以及何时使用shell而不是Ruby