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.

Share it!

There’s just one person behind this website; if this article was helpful (or interesting), I’d appreciate it if you’d share it. Thanks, Al.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.