Posts Tagged Unix
How to Write a Self-Executing Ruby Script
Posted by Phillip Lemky in Passionate Programming on June 26, 2010
Let me state right off that I’m a Ruby newbie and Rails rookie. Last week, I became acquainted with the language and framework when I had the distinct pleasure of attending a five-day Ruby on Rails boot camp. In addition to teaching us Ruby and Rails, our knowledgeable sensei instructed us in the ways of Test Driven Development and Behavior Driven Development. What an eye opener that experience was for me! Ruby, even without Rails, is such a powerful language. It seems to have all the power of Perl 5, but with none of Perl 5′s drawbacks. (One of those drawbacks is a clunky object system, but the Moose extension largely cures that ill.) Combined with Rails, it’s like nothing I’ve ever seen before: database abstraction, presentation abstraction, database versioning, and libraries (i.e., gems) for every imaginable need.
As part of my new-language learning process, if I discover something about the said language that’s cool or noteworthy, that may be of help to you, or that may assist me in my understanding of it by writing about it, I plan to write blog posts such as this one. Here’s something cool. Want to execute a Ruby script without having to run the Ruby interpreter? It’s as simple as doing the following. (Sorry, Unix-flavored systems only—such as OS X and Linux. This won’t work on Windows.)
- Find out where the Ruby interpreter lives on your machine. Type the following on the command-line.
which rubyOutput:
/usr/local/bin/ruby
- Create a new file. No file extension is necessary. The first line of the script should start off with #! (the shebang), followed by the above output. After that, enter your Ruby code.
#! /usr/local/bin/ruby puts "Iron Maiden rules!\n"
- Next, since we’re invoking our script—rather than the Ruby interpreter directly—we need to make it executable. (Usage of the shebang line will automatically invoke the Ruby interpreter on our behalf.) Some more typing on the command-line…
chmod +x example ls -l example
Output:
-rwxr-xr-x 1 phillip staff 52 26 Jun 19:47 example
- Now, the only thing left to do is to run our script. The last bit of typing on the command line…
./exampleOutput:
Iron Maiden rules!
And that’s it! We’ve just created a self-executing Ruby script. It should be noted that self-executing scripts, with the shebang line, can be done in other languages as well (such as Perl and Python).


Latest Comments