System Scripting with Scala

For the longest time I have used Ruby as my pocket knife for system scripting… you know, just knocking up small little executable files that run helpful tasks or automate yawnful processes. I like Ruby for this kind of thing and it works. Recently a coworker in marketing wanted some automation for something relatively simple and instead of using Ruby I thought i’d just knock it together with Scala and in doing so I came across a neat little thing with the Scala scripting support.

Assuming you have Scala installed, you can execute bash statements and pass them directly to your Scala code. This can be pretty handy as there are certain things that are particularly annoying to do from Scala (and more broadly with Java) like finding out where exactly you are executing too on the file system. Often if you use the good ol’ protection domain trick it will give you a location in /var/tmp, as opposed to the real location of the script. Consider the following:

SCRIPT="$(cd "${0%/*}" 2>/dev/null; echo "$PWD"/"${0##*/}")"
DIR=`dirname "${SCRIPT}"}`
exec scala $0 $DIR $SCRIPT


object App {
  def main(args: Array[String]): Unit = {
    val Array(directory,script) = File(_).getAbsolutePath)
    println("Executing '%s' in directory '%s'".format(script, directory))

Notice the base code between #!/bin/sh and ::!#. This allows you to execute bash script (or whatever script you want) before evaluating this file as a Scala script. This can be pretty handy for certain tasks when doing system scripting :-)

Assume you saved this file as “thing”, you can then execute it like any other script: ./thing


comments powered by Disqus