How to write a Scala shell script that reads input from STDIN

As a quick note, if you need an example of how to write a Scala shell script that reads from STDIN (standard input) and writes to STDOUT (standard output), this code shows a solution:

#!/bin/sh
exec scala -savecompiled "$0" "$@"
!#

import scala.io.StdIn

var line = ""
while ({line = StdIn.readLine(); line != null}) {
    println(line)
}

How to run it

On a Linux or Mac system you can name that file echo.sh, make it executable, and then use it in a Unix pipeline this:

$ cat /etc/passwd | echo.sh

All this script does is read from STDIN and write to STDOUT (so that’s not too exciting), but you can use it as a starting point for your needs: just put your custom code inside the while loop.

In my case I use code like this to filter some HTML files I’m processing. My code works in a manner that’s similar to using a sed script, but my needs are a little more complex than what I can accomplish with sed.

P.S. — If you don’t remember what savecompiled does, see this short example.

Summary

In summary, if you needed to see a way to read STDIN and write to STDOUT in a Scala shell script, I hope this example is helpful.