How to set the classpath in a Scala script (Scala shell script)

Scala script FAQ: How do I set the CLASSPATH in a Scala shell script?

If you need to set the CLASSPATH when executing a Scala script, use the exec command as shown in the following example:

exec scala -classpath "lib/htmlcleaner-2.2.jar:lib/scalaemail_2.9.1-1.0.jar:lib/stockutils_2.9.1-1.0.jar" "$0" "$@"

As you can see from that code, I'm adding three jar files to my classpath at the beginning of my Scala shell script.

If you’re having a problem where this isn’t working, it may be necessary to include the current directory as the “.” character at the beginning of that classpath, like this:

exec scala -classpath ".:lib/htmlcleaner-2.2.jar:lib/commons-lang3-3.1.jar" -savecompiled "$0" "$@"

Source code for a complete example

For the sake of completeness, here's the source code for a Scala script I wrote last night named

exec scala -classpath "lib/htmlcleaner-2.2.jar:lib/scalaemail_2.9.1-1.0.jar:lib/stockutils_2.9.1-1.0.jar" "$0" "$@"

import com.devdaily.stocks.StockUtils
import scala.collection.mutable.ArrayBuffer

object GetStocks {

  case class Stock(symbol: String, name: String, price: BigDecimal)

  val DIR = System.getProperty("user.dir")
  val SLASH = System.getProperty("file.separator")
  val CANON_STOCKS_FILE = DIR + SLASH + "stocks.dat"
  val CANON_OUTPUT_FILE = DIR + SLASH + "quotes.out"
  def main(args: Array[String]) {

    // read the stocks file into a list of strings ("AAPL|Apple")
    val lines = Source.fromFile(CANON_STOCKS_FILE).getLines.toList
    // create a list of Stock from the symbol, name, and by retrieving the price
    var stocks = new ArrayBuffer[(Stock)]()
    lines.foreach{ line =>
      val fields = line.split("\\|")
      val symbol = fields(0)
      val html = StockUtils.getHtmlFromUrl(symbol)
      val price = StockUtils.extractPriceFromHtml(html, symbol)
      val stock = Stock(symbol, fields(1), BigDecimal(price))
      stocks += stock
    // build a string we can output
    var sb = new StringBuilder
    stocks.foreach { stock =>
      sb.append("%s is %s\n".format(, stock.price))
    val output = sb.toString
    // write the string to the file
    val pw = new PrintWriter(new File(CANON_OUTPUT_FILE))



As the name indicates, I run that code as a normal Linux shell script. I make it executable with chmod +x, then run it.

That code needs some cleanup, but if you want to modify the CLASSPATH when running a Scala shell script, I hope the example is helpful.

Note: I've read elsewhere that you can use a wildcard like "lib/*.jar" when setting the classpath, but I haven't been able to get that to work, at least not on a Mac OS X (Unix) system.

As a final note, see the scala command man page for more information.