I often use shell scripts to automate mundane, repeatable tasks on my computer. Since I’ve found Groovy, though, I have discovered a great way to make writing those scripts easier and more enjoyable. This is especially true if I have anything complex to do, and it saves me a LOT of time. Allow me to elaborate.
Getting started with command-line Groovy
Like many of the tools I advocate here, you’ll want to grab Cygwin for the best experience.
There are thorough instructions for getting Groovy running within the Groovy documentation. Basically you just download a ZIP, extract it where you want, and add a couple environment variables.
Can be installed easily on Linux or Mac:
1 2 3
Now you can start writing shell scripts in Groovy. Let’s write a little script to test it out:
Actually, there are a ton of ways to run Groovy, but I’m just going to focus on scripts for now.
Bash vs. Groovy example
Let’s say I want to have a script that can check my friends’ last X tweets so I don’t have to leave my command-line to check twitter.
1 2 3 4 5 6 7 8
I really don’t want to read my tweets in XML. Being a Java guy, I wonder if there is a way we can harness it’s power. Groovy is basically enhanced Java so I can
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
And run it just like any shell script:
Groovy can certainly do much more than deal with XML, it is a full-featured dynamic language with great expressiveness. It is simply satisfying to write, and you can do everything a shell script can do and more.
As an extra treat, here is a Groovy script to update your twitter status, tweet.groovy:
1 2 3 4 5 6 7 8 9
I personally have a /scripts directory in my home dir which I put on my path, so to run the previous script I just have to type:
Ok, so if you’re fairly savvy with your old-school shell scripting, I don’t expect you to switch to Groovy for simple tasks. I see 2 major cases for using it:
- You need to do complex operations on data
- You know Java better than your shell scripting
If you like Groovy and want to learn more, you might consider checking out the Groovy docs.