I use bash every day of my life, which means I have a fondness for one-liners. The ability to smash complex commands as a series of pipes provides a type of satisfaction and pride not often found elsewhere. Unfortunately, not everything you want to do can be accomplished using Bash builtins or common CLI programs typically installed. Instead of hunting down the "proper" way to do it, you can hack something together like I prefer to do.
Let's say I know I want to do something, but I can'd find a reliable predictable way to do with with bash utilities. I happen to also know some ruby code that would do exactly what I want. I could write a ruby script to read in from a file and process and then output, but thats a lot of hassle for a task so small. Luckily, ruby makes it very easy for us to easily pipe text into the ruby interpreter and provide ruby code to do whatever we want with that input.
Or a bit convoluted with bash for loops:
The -n argument:
The -e argument:
Which is a little confusing but basically means "run ruby code provided as argument"
Thats nice, but what if I need to use a method provided by a gem thats not included in the standard ruby library? as easy as:
The -r argument:
Lastly, the -p argument can be of some use as well:
You can use -p instead of -n with a puts but things can get weird (does print at end of loop instead of puts):
You can even technically paste in scripts and have them run:
Just be careful with escaping your quotes:
Even if you try to escape the single quotes (Bash doesnt read it the way you think it should):
You'd have to use the Bash syntax ANSI strings (note the $ before the opening single quote):
Lot's of caveats and gotcha's to consider, know, and think about. Remember, pipe to ruby when it's simple and convenient. If you start getting too complicated with multiple lines and quote escapes, just put it in a file and run that instead.