Writing Ruby Scripts That Respect Pipelines
Want to write a Ruby program that behaves like grep
, cat
, or tail
? I wrote an article showing how you can make your Ruby scripts accept input via command line arguments or pipes. I show you how to differentiate your output so that you can output nicely formatted text for terminals, but always send plain text when you’re being piped to another program.
Comments
Excellent article! Thanks for taking the time to write it. Bookmarked for when I need to do this.
This is a really good article! I always get annoyed when Ruby scripts do not check if
$stdout
is a tty, and output color codes.less
will escape any color codes, making the output garbled.Responding to postmodern. That used to be the case long ago. Today, it seems
less
and other programs respect (or deal with) escape codes correctly. I am on OSX and ‘less’ works perfectly with such output. So doesmost
.Woot!
The way that
less
responds to color codes is also dependent on configuration. For exampleless -R
will try to preserve color codes coming from $stdin. I haveexport LESS=' -R'
in my .bashrc so that this is always on.Post a comment